Walter White
Walter White

Reputation: 1026

How to call function from child component in parent component

I have parent components

<div md-dialog-content>
  <div class="section-top">
    <p id="title" style="float:left;">Adding Dockument</p>
    <div md-dialog-actions style="float:right;">
      <button class="edm-button inline" md-button (click)="onNoClick()" tabindex="-1">Cancel</button>
      <button class="edm-button inline" md-button (click)="onClick()" tabindex="-1">Confirm</button>
    </div>
  </div>
  <div>
    <app-document-data [buttonMessage]="buttonMessage"></app-document-data>
  </div>
</div>

In Child component i have method onSubmit() { }

I have a question when to call onSubmit() function when i click a button confirm in parrent component.

I know that i probably should use @Input and @Output decorator but i don't know how properly.

Upvotes: 0

Views: 1374

Answers (2)

Swoox
Swoox

Reputation: 3740

In your parent component:

onClick(){
  this.buttonMessage = true;

In your child:

@Input() buttonMessage: boolean;

And a ngOnChanges:

ngOnChanges(changes: any) {
  if(changes.buttonMessage.currentValue){
     this.onSubmit();

Upvotes: 1

user4676340
user4676340

Reputation:

There's even easier : give your child a template reference, and you can call its functions like so : (I guess your second button will make the call)

<div md-dialog-content>
  <div class="section-top">
    <p id="title" style="float:left;">Adding Dockument</p>
    <div md-dialog-actions style="float:right;">
      <button class="edm-button inline" md-button (click)="onNoClick()" tabindex="-1">Cancel</button>
      <button class="edm-button inline" md-button (click)="appDD.onSubmit()" tabindex="-1">Confirm</button>
    </div>
  </div>
  <div>
    <app-document-data #appDD [buttonMessage]="buttonMessage"></app-document-data>
  </div>
</div>

Upvotes: 1

Related Questions