【发布时间】:2017-10-13 23:39:44
【问题描述】:
我有一个包含子组件列表的父组件。此子项是动态创建的,可以是任何类型。
所以,我正在做的是在父组件中使用 ng-container 作为主机,使用 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();
}
}
现在,我的问题。我需要子组件对其属性的更改做出反应,但由于它的属性不是输入,而只是基本属性,所以我不能在子组件中使用 ngOnChanges。那么有没有办法让子组件订阅父组件的变化呢?
我可以在 Host 指令中使用 ngOnChanges 并更新组件中的属性,但是如何触发子组件中的一些代码?
我有一个plunker 来测试它。当点击data1、data2、data3或data4时,下面的行应该折叠或展开。
谢谢。
【问题讨论】:
标签: angular