簡體   English   中英

在Angular 2中將函數從Parent傳遞給Child組件

[英]Pass function from Parent to Child component in Angular 2

我在Parent Component中有一個Array( mMemberCount ),根據這個數組的大小,子組件(Reusable)附加到Parent組件。

<member-template *ngFor="let item of mMemberCount" [title]="item.relation" [memberid]="item.id" (update)="update($event)">
</member-template>

<div class="btn_container">
  <button class="button orange" type="submit">Submit</button>
</div>

子組件如下

  @Component({
      selector: 'member-template',
      templateUrl: './member-template.component.html',
      styleUrls: ['./member-template.component.scss'],
      providers: [],
    })

    export class MemberTemplateComponent implements OnInit {

      TAG: string = " MEMBER-TEMPLATE: ";
      // Input variables wil be taken from the calling
      @Input('title') title: string;
      @Input('memberid') memberId: number;

      @Output('update')
      datasubmit: EventEmitter<string> = new EventEmitter<string>();


      sendDataToParent(){
         let output = "Tetsing Eventemitter";
         this.datasubmit.emit(output);
      } 
    }

@output('update')工作正常。 我想從ParentComponent調用ChildComponent(MemberTemplateComponent)的sendDataToParent () 我的意思是當用戶點擊父組件的按鈕提交時,此sendDataToParent應該調用

更新於11/15/17

您可以使用@ViewChild實現此目的

為父級

import { AfterViewInit, ViewChild } from '@angular/core';
import { Component }                from '@angular/core';
import { MemberTemplateComponent }  from './member.template.component';

@Component({
      selector: 'parent-template',
      templateUrl: './parent-template.component.html',
      styleUrls: ['./parent-template.component.scss'],
      providers: []
})

export class ParentTemplateComponent implements OnInit {
    @ViewChild(MemberTemplateComponent) private childComponent: MemberTemplateComponent;
    ngAfterViewInit() {
         submit() {
              this.childComponent.sendDataToParent(); 
         }
    }
}

最后找到了我在ParentComponent中使用@ViewChildren的解決方案

  @ViewChildren('component') components: QueryList<MemberTemplateComponent>;

兒童組件 -

<member-template #component *ngFor="let item of mMemberCount" [title]="item.relation" [memberid]="item.id" (update)="update($event)">
</member-template>

迭代Component QueryList

 this.components.forEach(component => {
      component.callChildMethod();
    });

現在從parentComponent調用多個子組件的callChildMethod()

干杯...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM