Angular trigger function from outside component

752 Views Asked by At

I have a component that only contains a form and a function to submit the form.

submitData(newUserForm: NgForm)

How can I trigger this function from another component, when I click a button?

I embed the form component like this:

<app-form></app-form>

But it's not created in the main component and I cannot import it, like a child component.

I have a service in the main component but the form component doesn't have access to it.

I have found this but nothing seem to work for me.

How to call another components function in angular2

In the main component I need a function that should call the submit function from the form:

Something like:

save() {
   submitData();
}

Does it work with something like Hostlistener, dispatchEvent or runOutsideAngular?

I have found some samples but nothing seem to work.

2

There are 2 best solutions below

2
Liu Zhang On

This is about the component interaction. Just try with @ViewChild decorator, or you can interact them using service.

0
Mr.UV On

After reading the problem I think you want to call the "submitData" method of "form" component whenever "save" method gets called on parent component. For this you can use "@Input()" method. it is generally used for passing the data from parent to child component same as our case.

So the solution will be something like below.

On parent component declare on property

isSubmitted: boolean = false;

then in the set this variable to true when the method "save()" gets called on parent.

save() {
    this.isSubmitted = true;
}

Now pass this variable to child component. to do this you need to pass this variable like below from parent template file.

<app-form [isSubmitted]="isSubmitted"></app-form>

Now that we are passing data from parent component we need to listen for the changes on child component. in child component we need to declare a "@Input()" directive like below.

export class Form {

@Input() isSubmitted: boolean;
 ...
}

after declaring this property we can now listen for the changes whenever the variable gets changed in parent component.

export class Form implements OnChanges {
     @Input() isSubmitted: boolean;
     ...

     // this is the angular life cycle hook which detects changes in input bound properties ( in our case "isSubmitted")
     ngOnChanges(changes: SimpleChanges) {
          if(changes && changes['isSubmitted'].currentValue){
               // calling the submit data method if the "isSubmitted" value changes to "true" from parent component.
               this.submitData(newUserForm: NgForm);
          }
     }
}

So this is how parent => child communication gets done in angular. Feel free to ask for any doubts. For more info you can check this link: parent-child-communication