angular - ViewChildren 找不到动态组件

标签 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>

我错过了什么吗?

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

  }
}

动态组件

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

突出显示指令

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

最佳答案

那是行不通的,因为 @ViewChildren 只查询它自己的 View ,而不是子组件中包含的 View 。您的动态组件是一个具有自己 View 的子组件。

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

关于angular - ViewChildren 找不到动态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43102427/

相关文章:

Angular Material io MatDatePicker

css - 如何增加 mat-accordion 中箭头的大小

css - ionic 4 : changing ion-content background does not work

angular - 带有 Angular 的 Webpack 别名 - 不能使用命名空间 'UtilsService' 作为类型

angular - RxJS 重构嵌套 map 语句

node.js - 执行 npm install 时出现 Azure DevOps CI 代理错误

Angular 2 路由器导航无法使用相同的 url 第二次工作

Angular 元素作为 react 形式的原生表单控件

angular - Ng2-charts 应用程序不显示图表

javascript - 制作一个 Angular 2 按钮组件,将用户带到网页顶部