gpt4 book ai didi

angular - 从 Angular 中的模板引用变量中获取 ElementRef

转载 作者:行者123 更新时间:2023-12-04 04:18:48 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Access DOM element with template reference variables on component

(2 个回答)


2年前关闭。




在下面的代码中

<input #myRef1 />
<input #myRef2 my-custom-attribute />
#myRef1将是 ElementRef , 和 #myRef2将是 MyCustomAttributeComponent指示。基本上,它隐式地找到第一个组件并将其与模板引用变量相关联。
感谢 exportAs,我可以强制使用我想要的指令/组件,但在这里,我实际上想要 ElementRef在这两种情况下。

有什么要强求的 #myRef2成为 ElementRef 没有 typescript @ViewChild(..., { read: ElementRef }) .我需要访问 myRef2作为 ElementRef在我的模板中。

最佳答案

在指令中注入(inject) ElementRef 服务,然后像这样在模板中访问注入(inject)的服务引用

组件.html

<input #ref="custom" type="text" appCustom>
{{ref.template}}

指令.ts
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appCustom]',
exportAs: 'custom'
})
export class CustomDirective {
constructor(public template:ElementRef) { }
}

关于angular - 从 Angular 中的模板引用变量中获取 ElementRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59964438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com