订阅Angular中父组件的更改
发布时间:2020-12-17 07:11:05 所属栏目:安全 来源:网络整理
导读:我有一个父组件,它包含一个子组件列表.这些孩子是动态创建的,可以是任何类型. 所以,我正在做的是在父组件中使用ng-container作为主机,使用ComponentFactoryResolver创建子组件,然后使用“`(component.instance as any)更新子组件中的一些属性.id = host .ID;
我有一个父组件,它包含一个子组件列表.这些孩子是动态创建的,可以是任何类型.
所以,我正在做的是在父组件中使用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(); } } 现在,我的问题.我需要子组件来响应其属性的变化,但由于它的属性不是输入而只是基本属性,我不能在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 }) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |