[英]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.