问题描述
我目前正在研究仅操作dom元素的指令.
I am currently working on a directive which simply manipulates the dom elements.
我想访问作为指令宿主的元素的模板变量,但由于结果始终是不确定的,因此我无法执行此操作.
I wanted to access to template variables of the element which is the host of the directive, but I was unable to do that, because the result is always undefined.
指令:
@Directive({
selector: '[sample-directive]'
})
export class SampleDirective implements AfterViewInit {
@ViewChild('queryMe') queryMe: ElementRef;
ngAfterViewInit(): void {
console.log(this.queryMe);
}
}
sampleComponent.template.html:
sampleComponent.template.html:
<div #queryMe></div>
用法:
<sample-component [sample-directive]></sample-component>
是否可以使用这样的模板变量?
Is it possible to use template variables like that?
推荐答案
将模板变量发送到指令:堆栈闪电
Send the template variables over to your directive : stackblitz
@Input('appQuery') appQuery: HTMLElement;
<div [appQuery]="queryMe">
<div #queryMe></div>
</div>
编辑
第二个解决方案:为您的可查询元素提供自定义属性.由于模板变量只是对HTML元素的引用,因此您将获得几乎相同的结果(除了标签中的另一个属性).
EDIT
Second solution : provide custom attributes to your query-able elements. Since template variables are just references to HTML elements, you will get pretty much the same result (except for one more attribute in your tag).
get element() { return this.el.nativeElement; }
ngAfterViewInit() {
console.log(this.element.querySelector('[queryMe]'));
}
<div appQuery>
<div queryMe></div>
</div>
这篇关于通过angular中的指令访问模板变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!