[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 .
相关文章
- Tensorflow入门教程(五十二)——Inter-UNet&TW-Inter-UNet
- 每日tips:Dart & Flutter Easy Wins 8-14
- Git-命令速查与相关问题解决-Cheatsheet & Troubleshooting
- tcp和udp的面试题_adp转化为amp
- 关于 Angular 工程文件 angular.json 里的 inlineCritical 属性
- 7 Papers & Radios | 一句话为视频加特效;迄今为止最全昆虫大脑图谱
- 7 Papers & Radios | 几分钟说话视频实现虚拟数字人复刻;ICLR 2021八篇杰出论文
- 当dex分包遇上NoClassDefFoundError&ClassNotFoundException
- JVM attach & ASM
- netbios amp DDOS攻击.c
- 小偷&小偷入库&采集入库
- 学习YUI.Ext第七天--关于View&JSONView
- 【消息提示组件】,兼容IE6/7&&FF2