【问题标题】:Subscribe to changes in parent component in Angular订阅 Angular 中父组件的更改
【发布时间】: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


    【解决方案1】:

    子组件无法监听父组件的变化,但您可以通过调用子组件的方法来通知它们更改:

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

    【讨论】:

    • 谢谢!但是当TypeError: innerComponents[this.id].ngOnChanges is not a function 成为您在答案中建议的数组的innerComponents 时出现错误。我的 ChildComponent 实现了 OnChanges,但是方式。
    • 什么是this.id?组件实际上有ngOnChanges 方法吗? .instance 也不见了
    • 抱歉,您是对的,.instance 丢失了。现在可以用了,谢谢!!
    【解决方案2】:

    【讨论】:

    • 不,子组件中更改的属性不是子组件更改而是父组件更改,因此我无法知道子组件何时更改。
    猜你喜欢
    • 2018-03-15
    • 2021-11-25
    • 2021-06-07
    • 2021-12-14
    • 2019-01-25
    • 2020-09-15
    • 1970-01-01
    • 2021-05-14
    • 2016-11-23
    相关资源
    最近更新 更多