首页 文章

订阅Angular中父组件的更改

提问于
浏览
6

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

所以,我正在做的是在父组件中使用 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时,下面的行应该折叠或展开 .

谢谢 .

2 回答

  • 3

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

    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
      })
    }
    
  • 0

相关问题