angular - 在没有包装器 ViewChild 的情况下从组件代码访问 ng-content

标签 angular typescript angular5 angular6

假设我有一个名为 RecursiveComponent 的组件(带有一个名为 recursive 的选择器)。它有一个数字“标识符”作为输入,并在其主体中接受更多的 RecursiveComponents。所以使用该组件的 HTML 代码可能如下所示:

<recursive identifier="1">
  <recursive identifier="2">
    <recursive identifier="3"></recursive>
  </recursive>
  <recursive identifier="4"></recursive>
</recursive>

为简单起见,该组件仅输出“identifier has x children”,然后是通过 <ng-content> 完成的插入主体.这行得通,但要弄清楚有多少子组件,我必须用 ViewChild 包装 ng-content 并查看 nativeElement 的 childNodes,我觉得这有点矫枉过正。这是组件代码的样子:

@Component({
  selector: 'recursive',
  template: `
    {{identifier}} has {{noOfChildren}} children 
    <div #contentRef>
      <ng-content select="recursive"></ng-content>
    </div>`
})
export class RecursiveComponent implements OnChanges {
  @ViewChild('contentRef', { read: ElementRef }) contentRef: ElementRef;

  @Input() identifier: number;

  noOfChildren: number;

  ngOnChanges() {
    if (this.contentRef) {
      this.noOfChildren = this.contentRef.nativeElement.childNodes.length;
    }
  }
}

是否有更好、更像 Angular 的方式来从组件代码中访问 ng-content?这感觉像是黑客攻击。

工作演示:https://stackblitz.com/edit/angular-wz8zu6

最佳答案

我认为这可能是您可以执行此类操作的唯一方法,您需要访问 DOM 中的元素。然而,还有另一种(可能更好的)方法可以使用@ViewChildren 来做到这一点。

You can use ViewChildren to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.

https://angular.io/api/core/ViewChildren#viewchildren

关于angular - 在没有包装器 ViewChild 的情况下从组件代码访问 ng-content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52149483/

相关文章:

typescript :从联合中的所有接口(interface)中省略一个属性,但保留联合结构

javascript - Angular cli 项目 - 更改路线时脚本未正确加载

javascript - Angular 5 BehaviorSubject 不适用于 bool 值

javascript - 多个主题和订阅或只有一个 - Angular 5

angular - Angular 2-管道排序-正确的语法

javascript - 如何让 Angular 识别绑定(bind)中的 HTML?

angular - 构建 Angular 6 库时为导出符号生成的元数据中遇到错误

javascript - Angular2 + Webpack : how to optimise vendor bundle

javascript - 在 Angular 2 App 中转换双向绑定(bind)属性中的日期

javascript - 以编程方式将 TypeScript 字符串编译为 Javascript 字符串