Angular ElementRef

在应用层直接操作 DOM,就会造成应用层与渲染层之间强耦合,导致我们的应用无法运行在不同环境,如 web worker 中,因为在 web worker 环境中,是不能直接操作 DOM。有兴趣的读者,可以阅读一下以下文章。通过 ElementRef 我们就可以封装不同平台下视图层中的 native 元素 (在浏览器环境中,native 元素通常是指 DOM 元素),最后借助于 Angular 提供的强大的依赖注入特性,我们就可以轻松地访问到 native 元素。

Web Workers 中支持的类和方法
1.导入ElementRef ViewChild

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

html 文件代码

 

Welcome to Angular World

Hello {{ name }}

2.声明

@ViewChild('greet')
  greetDiv: ElementRef;

3.使用

ngAfterViewInit() {
    // this.greetDiv.nativeElement.style.backgroundColor  = 'red';
    this.renderer.setElementStyle(this.greetDiv.nativeElement, 'backgroundColor', 'red');
  }

你可能感兴趣的:(Angular ElementRef)