gpt4 book ai didi

angular - 获取对模板中组件的引用

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:35 25 4
gpt4 key购买 nike

我想从模板中定义的组件中获取引用。让我们考虑一下我有以下组件:

@Component({
selector: 'a-component'
})
@View({
template: '<another-component #anotherComponent></another-component>',
directives: [AnotherComponent]
})
class AComponent {

callAnotherComponent() {
anotherComponent.doSomething();
}

}

显然这是行不通的,我的类中的另一个组件没有定义。但是有什么简单的方法可以做到这一点吗?在我的例子中,AnotherComponent 应该是一个弹出组件,我想简单地调用类似 myPopupCmp.showMessage("message") 的东西。

我当然可以使用数据绑定(bind)并在我的模板中像这样使用它:<another-component [text]="popupText" [visible]="isPopupVisible"></another-component> , 并使用这两个成员来显示它,首先设置文本,然后使其可见。在大多数情况下,数据绑定(bind)是有意义的,但在这里我想封装属性并避免在使用它的地方处理弹出窗口的行为。

编辑:

@EricMartinez 经过一些研究我已经更新了你的 plnkr,这里有一个链接到 fork :plnkr .诀窍是使用@ViewQuery,它用于查询组件 View 中的指令和dom 元素。我在这个问题中发现了这个:angular2 github .

现在的问题是 _results 似乎变空了,尽管如果我在控制台中展开 View 我可以看到我的组件,我什至可以看到它的属性,所以数据以某种方式存在但我无法访问它。有没有使用 QueryLists 的特殊方法?使用 _results 似乎不太干净,因为 _ 表示它应该是私有(private)的或内部的。我也尝试先使用,但它总是带来空引用。

最佳答案

截至https://github.com/angular/angular/commit/b0e2ebda708cf25287a211a30ef63d84cdb92a7f你应该能够做到:

class AComponent {
constructor(@Query('#anotherComponent') query:QueryList<AnotherComponent>) {

}
}

关于angular - 获取对模板中组件的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com