Angular父组件侦听ng-content子组件

时间:2018-11-01 20:10:01

标签: angular angular5 angular6

当子组件发出事件时,我希望函数在父组件中触发。子组件通过ng-content传递给父组件。我简化了我要执行的操作的代码,但似乎无法让孩子向父母投降。我想通过ng-content传递孩子,因为子组件可以是多种组件,而不是一个特定的组件

示例:

main.ts

<parent-component>
  <child-component></child-component>
</parent-component>

parent.component.ts

<div>
 {{ this.value }}
 <ng-content (updated)="updateParentValue()"></ng-content> <-- this doesn't work
</div>

updateParentValue(value) {
  this.value = value;
}

child.component.ts

<div>
  <span (click)="updateStuff()">update</span>
</div>

@Output() updated = new EventEmitter();

updateStuff() {
  // Stuff
  this.updated.emit(this.value);
}

1 个答案:

答案 0 :(得分:2)

感谢Krim,通过该链接解决了

main.ts

<parent-component>
  <child-component></child-component>
</parent-component>

parent.component.ts

<div>
 {{ this.value }}
 <ng-content></ng-content>
</div>

@ContentChildren(ChildComponent) childComponents: QueryList<ChildComponent>;

ngAfterViewInit() {
   this.childComponents.forEach((childComponent: ChildComponent) => {
       childComponent.updated.subscribe((item) => this.updateParentValue(item));           
   });
}

updateParentValue(value) {
  this.value = value;
}

child.component.ts

<div>
  <span (click)="updateStuff()">update</span>
</div>

@Output() updated = new EventEmitter();

updateStuff() {
  // Stuff
  this.updated.emit(this.value);
}