【问题标题】:@ContentChild not working in directive applied to custom component@ContentChild 在应用于自定义组件的指令中不起作用
【发布时间】:2020-06-10 05:55:20
【问题描述】:

我有一个自定义组件,它是一个<h1> 标记和一个<input> 标记。我希望能够从我的自定义指令访问输入,但是当我尝试使用 Angular 的@ContentChild 属性时,它始终是undefined。 如果我将自定义指令应用于本机 <input>,它可以正常工作。

我在这里设置了一个 StackBlitz 来强调这个问题:https://stackblitz.com/edit/using-contentchild-in-directive

如果您在页面加载后打开 JavaScript 控制台,您将看到:

Native Component: ElementRef {nativeElement: input}
Custom Component: undefined

如何从指令访问自定义组件中的<input>

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    这个行为是因为你正在访问contentChild,而Template Reference Variable 称为control

    @ContentChild('control',null) public ctrlByName: any;
    

    它只分配给input元素:

    <input  #control name="Native Component" testDirective />
    

    这就是为什么test-component 没有被ContentChild 检测到

    所以你实际上可以将elElementRef 分配给你的元素,它会正常工作,你不需要ContentChild

    constructor(private el: ElementRef) {
        this.name = el.nativeElement.attributes.name.value;
        this.ctrlByName = el;
    }
    

    Working DEMO

    【讨论】:

    • 现在你说Template Reference Variable 我完全明白为什么我的代码不能以这种方式工作了。
    • 我还添加了一个工作示例,请看一下
    猜你喜欢
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2018-02-20
    • 2015-11-02
    • 1970-01-01
    • 2019-08-15
    • 2018-02-06
    • 2016-11-07
    相关资源
    最近更新 更多