使用组件上的模板引用变量访问 DOM 元素

rob*_*rob 6 javascript angular2-template angular

我正在尝试使用模板引用变量获取对 Angular 2 模板中组件的 DOM 元素的引用。这适用于普通的 html 标签,但对组件有不同的行为。例如

<!--var1 refers to the DOM node -->
<div #var1></div>

<!--var2 refers to the component but I want to get the DOM node -->
<my-comp #var2></my-comp>
Run Code Online (Sandbox Code Playgroud)

有没有办法强制模板引用变量引用 DOM 节点,即使它在组件上?如果是这样,它是否包含在任何地方的文档中?我能找到的唯一文档在这里https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ref-vars他们没有详细介绍变量如何得到解决。

kem*_*sky 7

这取决于您将如何使用此参考。

1) 没有直接的方法在模板中获取组件 DOM 引用:

 import {Directive, Input, ElementRef, EventEmitter, Output, OnInit} from '@angular/core';

 @Directive({selector: '[element]', exportAs: 'element'})
 export class NgElementRef implements OnInit
 {
    @Output()
    public elementChange:EventEmitter<any> = new EventEmitter<any>();

    public elementRef:ElementRef;

    constructor(elementRef:ElementRef)
    {
        this.elementRef = elementRef;
        this.elementChange.next(undefined);
    }

    @Input()
    public get element():any
    {
        return this.elementRef.nativeElement;
    }

    public set element(value:any)
    {

    }

    ngOnInit():void
    {
        this.elementChange.next(this.elementRef.nativeElement);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

<my-comp [(element)]="var2"></my-comp>
<p>{{var2}}</p>
<!--or-->
<my-comp element #var2="element"></my-comp>
<p>{{var2.element}}</p>
Run Code Online (Sandbox Code Playgroud)

2)您可以在拥有模板的组件中获取此引用@ViewChild('var2', {read: ElementRef})

  • 所以四年后,我在 StackOverflow 上搜索了自己的答案! (5认同)