[英]Subscribe to changes in parent component in Angular
我有一个父组件,它包含一个子组件列表。 这些孩子是动态创建的,可以是任何类型。
所以,我正在做的是在父组件中使用ng-container
作为主机,使用ComponentFactoryResolver
创建子ComponentFactoryResolver
,然后使用```(component.instance as any)更新子组件中的一些属性.id = host .ID;````
这是父组件的代码(它是一个包含一些行的表):
<tr class="table-collapse__item" [class.active]="company === selected">
<td [attr.colspan]="getItemColspan()">
<ng-container host [id]="name" [selected]="isSelected"></ng-container>
</td>
</tr>
host
是一个指令
@Directive({
selector: '[host]'
})
export class Host implements OnChanges {
@Input() id: any;
@Input() selected: boolean;
constructor(public viewRef: ViewContainerRef) {}
}
最后是如何创建组件和更新属性
@ViewChildren(Host) hosts: QueryList<Host>;
constructor(private resolver: ComponentFactoryResolver,
private cd: ChangeDetectorRef) {}
ngAfterViewInit() {
if (this.hosts) {
const componentFactory = this.resolver.resolveComponentFactory(this.inner);
this.hosts.forEach((host: Host) => {
const component = host.viewRef.createComponent(componentFactory);
(component.instance as any).id = host.id;
(component.instance as any).selected = host.selected;
});
this.cd.detectChanges();
}
}
现在,我的问题。 我需要子组件来响应其属性的变化,但由于它的属性不是输入而只是基本属性,我不能在childComponent中使用ngOnChanges。 那么我可以通过一种方式从子组件订阅父组件中的更改吗?
我可以在Host指令中使用ngOnChanges并更新组件中的属性,但是如何在子组件中触发一些代码?
我有一个plunker进行测试。 单击data1,data2,data3或data4时,下面的行应该折叠或展开。
谢谢。
子组件无法监听父组件中的更改,但您可以通过调用子组件上的方法来通知他们有关更改:
components = [];
ngAfterVeiwInit() {
if (this.hosts) {
const componentFactory = this.resolver.resolveComponentFactory(this.inner);
this.hosts.forEach((host: Host) => {
const component = host.viewRef.createComponent(componentFactory);
(component.instance as any).id = host.id;
(component.instance as any).selected = host.selected;
this.components.push.components();
});
this.cd.detectChanges();
}
}
ngOnChanges() {
this.components.forEach((c) => {
c.instance.ngOnChanges(); // or any other method the child comonents have
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.