首页 > 解决方案 > Angular 8:问题查找通过多个 ng-content 嵌套的组件

问题描述

尝试查找嵌套在子子组件中的组件时,我遇到了这个问题。

我创建了一个我想要实现的示例:

import { Component, OnInit, ContentChildren, ElementRef, QueryList } from '@angular/core';


@Component({
  selector: 'app-grand-parent',
  template: '<ng-content></ng-content>',
})
export class GrandParentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'app-parent',
  template: '<ng-content></ng-content>',
})
export class ParentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}


@Component({
  selector: 'app-child',
  template: '<ng-content></ng-content>',
})
export class ChildComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}


@Component({
  selector: 'app-child-profile',
  template: '<div>Child Profile</div>',
})
export class ChildProfileComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'my-app',
  template: `
  <div>
  <app-grand-parent>
    <app-parent>
      <app-child>
      <app-child-profile></app-child-profile>
      <app-child-profile></app-child-profile>
      <app-child-profile></app-child-profile>
      </app-child>
    </app-parent>
  </app-grand-parent>
</div>`
})
export class AppComponent implements AfterContentInit  {
  @ContentChildren(ChildProfileComponent) profiles: QueryList<ChildProfileComponent>;

  ngAfterContentInit(): void {
    console.log(this.profiles);
  }
}

以下链接中有一个完整的示例: https ://stackblitz.com/edit/angular-rqh8gm

我不想使用ngProjectAs,因为我想动态查询元素。

我可以通过其父组件找到该组件。有没有办法将它重新附加到祖父组件?

标签: angulartypescript

解决方案


用于获取配置文件组件的对象。您需要在 app-child 组件中查询它

1)您在 Appcomponent 中找到它,但它没有直接投影在其中,因此您将无法找到它

2)您将其投影在 app-child 中,因此这将在 app-child 中可用

3) 示例

在上述情况下,comp3 投影在 comp2 内部而不是 comp1 中。直接投影在这里工作

看一看

https://stackblitz.com/edit/angular-hwv8g7?embed=1&file=src/app/app.component.ts

如果您想要 Appcomponent 中的访问计数,请尝试此操作。为此,您必须经过多个循环

https://stackblitz.com/edit/angular-shh1up?embed=1&file=src/app/app.component.ts

这是我的方法,如果您找到更好的方法,请告诉我


推荐阅读