使用组件上的模板引用变量访问 DOM 元素 [英] Access DOM element with template reference variables on component

查看:22
本文介绍了使用组件上的模板引用变量访问 DOM 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get a reference to the DOM element for a component in an Angular 2 template using a template reference variable. This works on normal html tags but has a different behaviour on components. e.g.

<!--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>

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

Is there any way force the template reference variable to refer to the DOM node even if it is on a component? And if so is it covered in the docs anywhere? The only docs I can find on this are here https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ref-vars and they don't go into much detail on how the variables are resolved.

推荐答案

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

It depends on how you are going to use this reference.

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

1) There is no straight way to get component DOM reference within template:

 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);
    }
}

用法:

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

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

2) You can get this reference in component that owns template with @ViewChild('var2', {read: ElementRef}).

这篇关于使用组件上的模板引用变量访问 DOM 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆