【问题标题】:Access DOM element with template reference variables on component使用组件上的模板引用变量访问 DOM 元素
【发布时间】:2017-06-30 05:21:55
【问题描述】:

我正在尝试使用模板引用变量获取对 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>

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

【问题讨论】:

    标签: javascript angular angular2-template


    【解决方案1】:

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

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

    用法:

    <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}) 模板的组件中获取此引用。

    【讨论】:

    • 4 年后,我在 StackOverflow 上搜索了自己的答案!
    【解决方案2】:

    从 Angular 8 开始,以下内容提供了对 ElementRef 和本机元素的访问。

    /**
     * Export the ElementRef of the selected element for use with template references.
     *
     * @example
     * <button mat-button #button="appElementRef" appElementRef></button>
     */
    @Directive({
        selector: '[appElementRef]',
        exportAs: 'appElementRef'
    })
    export class ElementRefDirective<T> extends ElementRef<T> {
        constructor(elementRef: ElementRef<T>) {
            super(elementRef.nativeElement);
        }
    }
    

    【讨论】:

    • 你能指出Angular repo中的代码吗?因为我根本找不到。它不在 Angular 8 中。
    • @jsgoupil 很抱歉造成混乱。我的意思是,据我测试,这段代码适用于 Angular 8。它不包含在 Angular 中。
    猜你喜欢
    • 2017-01-30
    • 2017-07-20
    • 2015-10-31
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    相关资源
    最近更新 更多