jsg*_*pil 5 angular angular-template-variable
在下面的代码中
<input #myRef1 />
<input #myRef2 my-custom-attribute />
Run Code Online (Sandbox Code Playgroud)
将会#myRef1是一个ElementRef, 并且#myRef2将会是MyCustomAttributeComponent指令性的。基本上,它隐式地找到第一个组件并将其关联到模板引用变量。我可以强制我想要哪个指令/组件,这要归功于exportAs,但在这里,我实际上在两种情况下都想要ElementRef。
有没有什么东西可以强制#myRef2成为一个ElementRef 没有TypeScript的东西@ViewChild(..., { read: ElementRef })。我需要在我的模板中myRef2作为 an进行访问ElementRef。
在指令中注入 ElementRef Service,然后像这样访问模板中注入的服务引用
组件.html
<input #ref="custom" type="text" appCustom>
{{ref.template}}
Run Code Online (Sandbox Code Playgroud)
指令.ts
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appCustom]',
exportAs: 'custom'
})
export class CustomDirective {
constructor(public template:ElementRef) { }
}
Run Code Online (Sandbox Code Playgroud)