【问题标题】:Access element tagnames from child in parent从父级中的子级访问元素标记名
【发布时间】:2019-09-08 18:10:39
【问题描述】:

我有两个组件,ParentComponent 和 ChildComponent:

parent.component.html

<child-selector #parent></child-selector>

parent.component.ts

@ViewChild('parent', { read: ElementRef }) parent: ElementRef<any>;


doThis(event) {
    this.parent.nativeElement.childNodes.forEach(e => {
        if (e.tagName === 'GRIDSTER-ITEM') {
          console.log("do stuff here");
        }
      });
}

child.component.html

<gridster>
    <grister-item></gridster-item>
<gridster>

child.component.ts

如果代码是同一个组件,则代码将起作用,子 html 将直接位于父级中,#parent 将位于元素 &lt;gridster&gt; 上。

我应该使用什么来代替 ElementRef? 或者也许是另一种解决方案?

【问题讨论】:

  • 你应该在你的父模板中使用&lt;ng-content&gt;&lt;/ng-content&gt;@ContentChildren装饰器来引用里面的组件

标签: angular


【解决方案1】:

您可以使 gridster-item 元素对子组件可用。

child.component.ts

@ViewChildren(GridsterItemComponent) gridsterItems;

parent.component.ts

@ViewChild(ChildComponent) childComponent;

doSomething() {
  this.childComponent.gridsterItems.callSomeMethod();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 2015-04-23
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多