我可以将 HTML 元素的 Angular #variableName 强制为 return ElementRef 吗?

Can I force an Angular #variableName for an HTML element to return an ElementRef?

如果我创建这样的按钮:

<button #myButton>My Button</button>

...并像这样使用 ViewChild

@ViewChild('myButton', { static: true }) createButton: ElementRef;

...那么 createButton 是(如声明的那样)一个 ElementRef,其中 createButton.nativeElement 是一个 DOM 元素。

但是,如果我这样做:

<button mat-raised-button #myButton>My Button</button>

...我的变量不再是 ElementRef,而是 MatButton 实例。

我真的希望变量保持 ElementRef。我该怎么做?

我见过像 <form #myForm="ngForm"... 这样的符号,它确保变量特别是 NgForm,或者 <input #firstName="ngModel"...> 以获得 NgModel

我尝试了 <button #myButton="elementRef" mat-raised-button... 以及该主题的一些不同变体,但它们都产生了编译错误。有没有类似的东西可以解决问题?

这是 Angular 的一个非常缺乏记录的方面。我什至找不到这些 references/variables 的正确术语。哈希参考?哈希变量?赫伯特?我知道像 #firstName="ngModel" 这样的事情的唯一原因是看到示例,而不是从阐明一般概念的文档。

要指定要查询的令牌,可以使用 ViewChild#read 参数,如 Angular 文档中所述:

read - Used to read a different token from the queried elements.

示例

@ViewChild('myButton', { read: ElementRef, static: true }) createButton: ElementRef;

Check the demo


This is a very poorly documented aspect of Angular. I can't even find the proper terminology for these kinds of references/variables. Hash reference? Hash variable? Herbert? And the only reason I know about things like #firstName="ngModel" is from seeing examples, not from documentation that spells out the general concept.

关于这个,有一个专门的部分,你可以查看here

鉴于问题,@developer033 的回答是正确的。但是,如果想在模板中直接使用模板引用变量而不是通过@ViewChild,也会出现同样的问题。为了完整起见,我将在此处包含一个答案。

简短的回答:不,你不能。但是我们可以通过编写我们自己的指令作为代理来让它工作:

@Directive({
  selector: "[injectRef]",
  exportAs: "elementRef",
})
export class InjectRefDirective extends ElementRef<unknown> {
  constructor(elementRef: ElementRef<unknown>) {
    super(elementRef.nativeElement);
  }
}

然后用作

<button injectRef #myRef="elementRef"></button>