简体   繁体   中英

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.

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>

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM