订阅Angular中父组件的更改

Dav*_*vid 6 angular

我有一个父组件,它包含一个子组件列表.这些孩子是动态创建的,可以是任何类型.

所以,我正在做的是ng-container在父组件中使用as主机,创建子组件,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>
Run Code Online (Sandbox Code Playgroud)

host 是一个指令

@Directive({
  selector: '[host]'
})
export class Host implements OnChanges {
  @Input() id: any;
  @Input() selected: boolean;
  constructor(public viewRef: ViewContainerRef) {}
}
Run Code Online (Sandbox Code Playgroud)

最后是如何创建组件和更新属性

@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();
    }
  }
Run Code Online (Sandbox Code Playgroud)

现在,我的问题.我需要子组件来响应其属性的变化,但由于它的属性不是输入而只是基本属性,我不能在childComponent中使用ngOnChanges.那么我可以通过一种方式从子组件订阅父组件中的更改吗?

我可以在Host指令中使用ngOnChanges并更新组件中的属性,但是如何在子组件中触发一些代码?

我有一个plunker进行测试.单击data1,data2,data3或data4时,下面的行应该折叠或展开.

谢谢.

Gün*_*uer 4

子组件无法侦听父组件中的更改,但您可以通过调用子组件上的方法来通知它们有关更改的信息:

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
  })
}
Run Code Online (Sandbox Code Playgroud)