相关疑难解决方法(0)

ViewChildren找不到动态组件

包含@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() { …
Run Code Online (Sandbox Code Playgroud)

angular

10
推荐指数
1
解决办法
4081
查看次数

标签 统计

angular ×1