ViewChildren找不到动态组件

cga*_*ian 10 angular

包含@ViewChildren的父组件不会返回动态创建的组件的结果.

容器组件包含一个highlight指令,动态生成的组件highlight在其模板中包含一个指令.查询时@ViewChildren查询长度返回1.预期结果是2.

从HTML中可以看出,DOM上肯定有两个高亮指令.

<container-component>
    <div></div>
     <dynamic-component ng-version="4.0.0">
        <div highlight="" style="background-color: yellow;">Dynamic!</div>
     </dynamic-component>
     <div highlight="" style="background-color: yellow;">Number of Highlights 
        <div></div>
     </div>
</container-component>
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

https://plnkr.co/edit/LilvHJgFjPHnPuaNIKir?p=preview

容器组件

@Component({
  selector: 'container-component',
  template: `
    <div #contentProjection></div>
    <div highlight>Number of Highlights {{highlightCount}}<div>
  `,
})
export class ContainerComponent implements OnInit, AfterViewInit {
  @ViewChildren(HighlightDirective) private highlights: QueryList<HighlightDirective>;
  @ViewChild('contentProjection', { read: ViewContainerRef }) private contentProjection: ViewContainerRef;

  constructor(
    private resolver: ComponentFactoryResolver
    ) {
  }

  ngOnInit() {
    this.createDynamicComponent();
  }

  ngAfterViewInit() {
    console.log(this.highlights.length);

    // Should update with any DOM changes
    this.highlights.changes.subscribe(x => {
      console.log(this.highlights.length);
    });
  }

  private createDynamicComponent(){
    const componentFactory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.contentProjection.createComponent(componentFactory);

  }
}
Run Code Online (Sandbox Code Playgroud)

动态组件

 @Component({
      selector: 'dynamic-component',
      template: `
        <div highlight>Dynamic!</div>
      `,
    })
    export class DynamicComponent {
    }
Run Code Online (Sandbox Code Playgroud)

突出指示

 @Directive({
      selector: '[highlight]'
    })
    export class HighlightDirective {
      constructor(private elementRef: ElementRef) {
         elementRef.nativeElement.style.backgroundColor = 'yellow';
      }
    }
Run Code Online (Sandbox Code Playgroud)

DRi*_*FTy 11

这不起作用,因为@ViewChildren只查询自己的视图,而不是子组件中包含的视图.您的动态组件是具有自己视图的子组件.

要解决此问题,您可以@ViewChildren在具有输出事件的动态组件中添加查询,以便让任何关心的人(您的父组件)知道存在新实例.