@viewchild for 指令始终返回元素引用而不是指令引用 - angular5

Aru*_*raj 2 angular-directive angular angular5

我目前正在开发一个项目,我需要根据组件传递一些 @input 值。因此,该指令将相应地发挥作用。但问题是我无法获得该指令的参考。相反,我只得到了 elementRef 作为回报。请参阅下面的 stackblitz 示例以获取更多参考。

https://stackblitz.com/edit/angular-feptw3

yur*_*zui 5

有多种方法可以修复它:

1)使用read选项:

@ViewChild("myCustomDir", { read: MyCustomDirective}) myCustomDir: MyCustomDirective;
Run Code Online (Sandbox Code Playgroud)

例子

也可以看看:

2)使用exportAs

指令.ts

@Directive({
  selector: "[myCustom]",
  exportAs: 'myCustom'
  ^^^^^^^^^^^^^^^^^^^^
})
export class MyCustomDirective {
  ...
}
Run Code Online (Sandbox Code Playgroud)

html

<h1 myCustom #myCustomDir="myCustom">
                           ^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

例子

也可以看看: