[Angular 2] 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 .

时间: 2024-12-13 15:15:45

[Angular 2] ElementRef, @ViewChild & Renderer的相关文章

ElementRef, @ViewChild &amp; 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: 'w

Angular 2 ElementRef

Angular 2 的口号是 - "一套框架,多种平台.同时适用手机与桌面(One framework.Mobile & desktop.)",即 Angular 2 是支持开发跨平台的应用,比如:Web应用.移动Web应用.原生移动应用和原生桌面应用等. 为了能够支持跨平台,Angular 2 通过抽象层封装了不同平台的差异,统一了 API 接口.如定义了抽象类 Renderer .抽象类 RootRenderer 等.此外还定义了以下引用类型:ElementRef.Temp

Angular 2 中的 ViewChild 和 ViewChildren

https://segmentfault.com/a/1190000008695459 ViewChild ViewChild 是属性装饰器,用来从模板视图中获取匹配的元素.视图查询在 ngAfterViewInit 钩子函数调用前完成,因此在 ngAfterViewInit 钩子函数中,才能正确获取查询的元素. @ViewChild 使用模板变量名 import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular

Angular 2 模板语法与常用指令简介

一.模板语法简介 插值表达式 <div>Hello {{name}}</div> 等价于 <div [textContent]="interpolate(['Hello'], [name])"></div> 模板表达式 1.属性绑定 1.1输入属性的值为常量 <show-title title="Some Title"></show-title> 等价于 <show-title [titl

[Angular] Create a ng-true-value and ng-false-value in Angular by controlValueAccessor

If you're coming from AngularJS (v1.x) you probably remember the ng-true-value and ng-false-value directive which allowed to map custom boolean values like "yes" or "no" or whatever other value you had, onto your HTML form. In this les

Angular 2 HostListener &amp; HostBinding

原文 https://www.jianshu.com/p/20c2d60802f7 大纲 1.宿主元素(Host Element) 2.HostListener 3.HostListenerDecorator 装饰器应用 4.HostBinding 5.HostBinding 装饰器应用 宿主元素(Host Element) 在介绍 HostListener 和 HostBinding 属性装饰器之前,我们先来了解一下 host element (宿主元素). 宿主元素的概念同时适用于指令和组件

Angular使用总结 --- 如何正确的操作DOM

无奈接手了一个旧项目,上一个老哥在Angular项目中大量使用了JQuery来操作DOM,真的是太不讲究了.那么如何优雅的使用Angular的方式来操作DOM呢? 获取元素 1.ElementRef  ---   A wrapper around a native element inside of a View. 在组件的 constructor中注入ElementRef,可以获取到整个组件元素的包裹. @Component({ selector: 'app-test-page', templ

Angular+ionic2+Echarts 实现图形制作

step1:添加插件echart; npm install echarts --save package.json文件中会在dependencies中添加echarts step2:运行cmd,创建echart-pie组件: ionic g component echart-pie echart-pie.html文件: <div #echart class="echart-pie"> </div> echart-pie.scss文件: echart-pie {

[Angular] Modify :before / :after value from Javascirpt

Let's say we want to dynamiclly change some style in :before or :after element. We cannot use NgStyle, it doesn's support this use case, what we can do: Using css variable + setProperty import { Component, ElementRef, ViewChild } from '@angular/core'