盐开水 發表於 2019-5-8 11:26:00

Angular ElementRef详解

<p>一.为什么要用ElementRef</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Angular 的口号是 - "一套框架,多种平台。同时适用手机与桌面 (One framework.Mobile &amp; desktop.)",即 Angular 是支持开发跨平台的应用,比如:Web 应用、移动 Web 应用、原生移动应用和原生桌面应用等。</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;为了能够支持跨平台,Angular 通过抽象层封装了不同平台的差异,统一了 API 接口。如定义了抽象类 Renderer(已废弃,现在用Renderer2) 、抽象类 RootRenderer 等。此外还定义了以下引用类型:</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1.&nbsp;ElementRef;</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2.TemplateRef;</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3.ViewRef ;</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 4.ComponentRef ;</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 5.ViewContainerRef&nbsp;;</p>
<p>二.ElementRef有什么作用</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;在应用层直接操作 DOM,就会造成应用层与渲染层之间强耦合,导致我们的应用无法运行在不同环境,如 web worker 中,因为在 web worker 环境中,是不能直接操作 DOM。有兴趣的读者,可以阅读一下&nbsp;Web Workers 中支持的类和方法这篇文章。通过&nbsp; &nbsp; &nbsp; &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp; ElementRef 我们就可以封装不同平台下视图层中的 native 元素 (在浏览器环境中,native 元素通常是指 DOM 元素),最后借助于 Angular 提供的强大的依赖注入特性,我们就可以轻松地访问到 native 元素。</p>
<p>三.如何使用ElementRef</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 先看需求:我们要实现一个组件成功加载另一个组件(本文中是遮罩的组件)并渲染完成后,改变遮罩文字层div的样式,接下来请看我是如何实现的;</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1.引入相关api</p>
<div class="cnblogs_code">
<pre>import {Component, OnInit, Input, Output, EventEmitter, AfterViewInit, ElementRef, ViewChild, Renderer2} from '@angular/core';</pre>
</div>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2.构造函数依赖注入</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 0, 1)">constructor( private elementRef: ElementRef,
            private renderer: Renderer2) {
}</span></pre>
</div>
<p>&nbsp; &nbsp; &nbsp; &nbsp;3.使用属性装饰符@ViewChild</p>
<div class="cnblogs_code">
<pre>&lt;div class="contents" ="content | translate" #divContent&gt;
&lt;/div&gt;</pre>
</div>
<p>&nbsp; &nbsp;</p>
<div class="cnblogs_code">
<pre>@ViewChild('divContent') greetDiv: ElementRef;</pre>
</div>
<p>&nbsp; &nbsp; &nbsp; 4.设置相关样式</p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">ngAfterViewInit() {
    this.renderer.setStyle(this.greetDiv.nativeElement, 'width', '3.60rem');
}
</pre>
</div>
<p>  </p><br><br>
来源:https://www.cnblogs.com/robinw666/p/10830794.html
頁: [1]
查看完整版本: Angular ElementRef详解