首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ViewChildren找不到动态组件

ViewChildren找不到动态组件
EN

Stack Overflow用户
提问于 2017-03-29 19:22:49
回答 1查看 7.4K关注 0票数 13

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

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

从HTML中可以看到,DOM上肯定有两个突出显示的指令。

代码语言:javascript
复制
<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>

我是不是遗漏了什么?

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

容器组件

代码语言:javascript
复制
@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);

  }
}

动态组件

代码语言:javascript
复制
 @Component({
      selector: 'dynamic-component',
      template: `
        <div highlight>Dynamic!</div>
      `,
    })
    export class DynamicComponent {
    }

高亮指令

代码语言:javascript
复制
 @Directive({
      selector: '[highlight]'
    })
    export class HighlightDirective {
      constructor(private elementRef: ElementRef) {
         elementRef.nativeElement.style.backgroundColor = 'yellow';
      }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-29 19:33:14

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

为了解决这个问题,您可以在动态组件中添加一个@ViewChildren查询,该组件具有一个输出事件,让任何关心它的人(您的父组件)都知道存在一个新实例。

票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43102427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档