【问题标题】:Angular - template reference on ng-contentAngular - ng-content 上的模板参考
【发布时间】:2020-05-23 18:34:39
【问题描述】:

我需要围绕 Angular 应用中的输入呈现动态内容。

我的想法是创建一个自定义组件,然后使用ng-content 将行为绑定到该输入。像这样:

<my-wrapper>
    <input type="text" otherAttributes...>
</my-wrapper>

我的包装器如下所示。

HTML:

<span>
    <ng-content #myRef></ng-content>
    <button (click)="perform(myRef)">Click me!</button>
</span>

和.ts函数:

perform(myRef: HTMLIntpuElement) {
    myRef.value = 'something else';
}

现在,我知道ng-content 实际上并不存在,而且我不能真正对其进行引用,因为该内容可以是多个元素,但是有没有办法获得它“Angular方式”,而不是使用蛮力,即本机元素?

【问题讨论】:

标签: angular typescript angular2-ngcontent


【解决方案1】:

我认为您的问题可以通过 @ContentChildren/@ContentChild 解决。 它们与@ViewChildren/@ViewChild 相似,但@ContentChild 会查看ng-content 而@ViewChild 则不会。

 <input type="text" #myRef>

在打字稿文件中:

 @ContentChildren('myRef') items: QueryList<ElementRef>;

【讨论】:

    猜你喜欢
    • 2020-02-21
    • 2017-08-28
    • 2017-06-30
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    相关资源
    最近更新 更多