ElementRef, @ViewChild & Renderer

Posted 枫叶布

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ElementRef, @ViewChild & Renderer相关的知识,希望对你有一定的参考价值。

ElementRef:

In Angular2 Doc, it suggest to "avoid" using ElementRef. It access DOM directly, can easily be attacked.

import {Component, OnInit, ViewChild, Renderer, ElementRef} from \'@angular/core\';

@Component({
    moduleId: module.id,
    selector: \'widget-three\',
    template: `<input type="text" #inputRef/>`
})
export class WidgetThree {

    constructor(private elm: ElementRef) {
        console.log("elm:", this.elm)

    }
}

If we log out the ElementRef, we can see, it refer to host element.

 

Renderer:

In the doc, it also suggest, if you want to change some dom prop, use Renderer instead. ElementRef can be just a reference to access native element object.

import { Directive, ElementRef, Input, Renderer } from \'@angular/core\';
@Directive({ selector: \'[myHighlight]\' })
export class HighlightDirective {
    constructor(el: ElementRef, renderer: Renderer) {
       renderer.setElementStyle(el.nativeElement, \'backgroundColor\', \'yellow\');
    }
}

This will set the host element background as yellow.

 

@ViewChild():

Access Child element by Ref or Class Object.

import {Component, OnInit, ViewChild, Renderer} from \'@angular/core\';

@Component({
    moduleId: module.id,
    selector: \'widget-three\',
    template: `<input type="text" #inputRef/>`
})
export class WidgetThree {

    @ViewChild(\'inputRef\') input;

    constructor(private renderer: Renderer) {
    }
    
    ngAfterViewInit(){
        this.renderer.invokeElementMethod(
            this.input.nativeElement,
            \'focus\',
            []
        );
    }
}

Here we have a ref "inputRef", we use ref to access input element.

\'invokeElementMethod\' will call the \'focus\' method the the input nativeElement which should be:

this.input.nativeElement.focus()

But the risk is on mobile it might have different method to focus on input, \'invokeElementMethod\' can safely help us to call the method .

转自:http://www.cnblogs.com/Answer1215/p/5898545.html

以上是关于ElementRef, @ViewChild & Renderer的主要内容,如果未能解决你的问题,请参考以下文章

在 html 中动态命名 div 并使用 @ViewChild('xyz') div: ElementRef;在角度

@ViewChild 返回未定义。我无法访问模式内的轮播 ElementRef

我应该如何在 Angular 8 中为 @ViewChild 使用新的静态选项?

angular 2 - 在 elementRef 上设置选择

elementRef的宽度发生变化时如何更改模板

Angular: 属性装饰器ViewChild终章