【问题标题】:Accessing ng-content from component code without a wrapper ViewChild在没有包装 ViewChild 的情况下从组件代码访问 ng-content
【发布时间】:2019-02-08 11:52:51
【问题描述】:

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

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

为简单起见,组件仅输出“identifier has x children”,然后是通过&lt;ng-content&gt; 完成的插入主体。这可行,但要弄清楚有多少子组件,我必须用 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?这感觉就像一个 hack。

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

【问题讨论】:

    标签: angular typescript angular5 angular6


    【解决方案1】:

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

    您可以使用 ViewChildren 获取元素的 QueryList 或 来自视图 DOM 的指令。任何时候添加子元素, 删除或移动,查询列表将被更新,并且更改 查询列表的 observable 将发出一个新值。

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

    【讨论】:

    • 好的,谢谢,我会调查的。我在想的是一个变量,它包含我可以通过某种 init 方法访问的内部内容,而无需模板引用。有点像你可以通过 AngularJS 中的链接方法获得的 transclude 函数。但我想这没关系
    • 是的,你可以做这样的事情,但它最终可能会成为一项更昂贵的操作。请您介意接受我的回答,将不胜感激。
    猜你喜欢
    • 2017-08-28
    • 2016-02-11
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多