Angular4里ElementRef的使用方法

这次给大家带来Angular4ElementRef的使用方法,Angular4里ElementRef使用的注意事项有哪些,下面就是实战案例,一起来看一下。

Angular 的口号是 – “一套框架,多种平台。同时适用手机与桌面 (One framework.Mobile & desktop.)”,即 Angular 是支持开发跨平台的应用,比如:Web 应用、移动 Web 应用、原生移动应用和原生桌面应用等。

为了能够支持跨平台,Angular 通过抽象层封装了不同平台的差异,统一了 API 接口。如定义了抽象类 Renderer 、抽象类 RootRenderer 等。此外还定义了以下引用类型:ElementRef、TemplateRef、ViewRef 、ComponentRef 和 ViewContainerRef 等。下面我们就来分析一下 ElementRef 类:

ElementRef的作用

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

ElementRef的定义

export class ElementRef { public nativeElement: any; constructor(nativeElement: any) { this.nativeElement = nativeElement; }}

登录后复制

ElementRef的应用

我们先来介绍一下整体需求,我们想在页面成功渲染后,获取页面中的 p 元素,并改变该 p 元素的背景颜色。接下来我们来一步步,实现这个需求。

首先我们要先获取 p 元素,在文中 “ElementRef 的作用” 部分,我们已经提到可以利用 Angular 提供的强大的依赖注入特性,获取封装后的 native 元素。在浏览器中 native 元素就是 DOM 元素,我们只要先获取 my-app元素,然后利用 querySelector API 就能获取页面中 p 元素。具体代码如下:

import { Component, ElementRef } from '@angular/core'; @Component({ selector: 'my-app', template: `  

Welcome to Angular World

hello {{ name }}

`,}) export class AppComponent { name: string = 'Semlinker'; constructor(private elementRef: ElementRef) { let pEle = this.elementRef.nativeElement.querySelector('p'); console.dir(pEle); }}

登录后复制

运行上面代码,在控制台中没有出现异常,但是输出的结果却是 null 。什么情况 ? 没有抛出异常,我们可以推断 this.elementRef.nativeElement 这个对象是存在,但却找不到它的子元素,那应该是在调用构造函数的时候,my-app 元素下的子元素还未创建。那怎么解决这个问题呢 ?沉思中… ,不是有 setTimeout 么,我们在稍微改造一下:

 constructor(private elementRef: ElementRef) { setTimeout(() => { // 此处需要使用箭头函数哈,你懂的...   let pEle = this.elementRef.nativeElement.querySelector('p');   console.dir(pEle);  }, 0); }

登录后复制

问题解决了,但感觉不是很优雅 ?有没有更好的方案,答案是肯定的。Angular 不是有提供组件生命周期的钩子,我们可以选择一个合适的时机,然后获取我们想要的 p 元素。

 import { Component, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'my-app', template: `  

Welcome to Angular World

hello {{ name }}

`,}) export class AppComponent { name: string = 'Semlinker'; // 在构造函数中 this.elementRef = elementRef 是可选的,编译时会自动赋值 // function AppComponent(elementRef) { this.elementRef = elementRef; } constructor(private elementRef: ElementRef) { } ngAfterViewInit() { // 模板中的元素已创建完成 console.dir(this.elementRef.nativeElement.querySelector('p')); // let greetp: HTMLElement = this.elementRef.nativeElement.querySelector('p'); // greetp.style.backgroundColor = 'red'; }}

登录后复制

运行一下上面的代码,我们看到了意料中的 p 元素。我们直接选用 ngAfterViewInit 这个钩子,不要问我为什么,因为它看得最顺眼咯。不过我们后面也会有专门的文章,详细分析一下 Angular 组件的生命周期。成功取到 p 元素,就剩下的事情就好办了,直接通过 style 对象设置元素的背景颜色。

功能虽然已经实现了,但还有优化的空间么?

import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';@Component({ selector: 'my-app', template: ` 

Welcome to Angular World

hello {{ name }}

`,}) export class AppComponent { name: string = 'Semlinker'; @ViewChild('greet') greetp: ElementRef; ngAfterViewInit() { this.greetp.nativeElement.style.backgroundColor = 'red'; }}

登录后复制

是不是感觉瞬间高大上了,不过先等等,上面的代码是不是还有进一步的优化空间呢 ?我们看到设置 p 元素的背景,我们是默认应用的运行环境在是浏览器中。前面已经介绍了,我们要尽量减少应用层与渲染层之间强耦合关系,从而让我们应用能够灵活地运行在不同环境。最后我们来看一下,最终优化后的代码:

import { Component, ElementRef, ViewChild, AfterViewInit, Renderer } from '@angular/core'; @Component({ selector: 'my-app', template: `  

Welcome to Angular World

hello {{ name }}

`,}) export class AppComponent { name: string = 'Semlinker'; @ViewChild('greet') greetp: ElementRef; constructor(private elementRef: ElementRef, private renderer: Renderer) { } ngAfterViewInit() { // this.greetp.nativeElement.style.backgroundColor = 'red'; this.renderer.setElementStyle(this.greetp.nativeElement, 'backgroundColor', 'red'); }}

登录后复制

1.Renderer API 还有哪些常用的方法 ?

export abstract class Renderer { // 创建元素 abstract createElement(parentElement: any, name: string,    debugInfo?: RenderDebugInfo): any; // 创建文本元素 abstract createText(parentElement: any, value: string,    debugInfo?: RenderDebugInfo): any; // 设置文本 abstract setText(renderNode: any, text: string): void; // 设置元素Property abstract setElementProperty(renderElement: any, propertyName: string,    propertyValue: any): void; // 设置元素Attribute abstract setElementAttribute(renderElement: any, attributeName: string,    attributeValue: string): void; // 设置元素的Class abstract setElementClass(renderElement: any, className: string,   isAdd: boolean): void; // 设置元素的样式 abstract setElementStyle(renderElement: any, styleName: string,    styleValue: string): void;  }

登录后复制

需要注意的是在 Angular 4.x+ 版本,我们使用 Renderer2 替代 Renderer (Angular V2)。

2.Renderer2 API 还有哪些常用的方法 ?

export abstract class Renderer2 { abstract createElement(name: string, namespace?: string|null): any; abstract createComment(value: string): any; abstract createText(value: string): any; abstract setAttribute(el: any, name: string, value: string, namespace?: string|null): void; abstract removeAttribute(el: any, name: string, namespace?: string|null): void; abstract addClass(el: any, name: string): void; abstract removeClass(el: any, name: string): void; abstract setStyle(el: any, style: string, value: any,   flags?: RendererStyleFlags2): void; abstract removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void; abstract setProperty(el: any, name: string, value: any): void; abstract setValue(node: any, value: string): void; abstract listen(   target: 'window'|'document'|'body'|any, eventName: string,   callback: (event: any) => boolean | void): () => void;}

登录后复制

相信看了本文案例你已经掌握了方法,更多精彩请关注【创想鸟】其它相关文章!

推荐阅读:

Immutable.js怎样实现撤销重做效果

vue判断input输入内容有否有空格

FileReader实现上传图片之前本地先预览

以上就是Angular4里ElementRef的使用方法的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2773236.html

(0)
上一篇 2025年3月8日 13:44:03
下一篇 2025年3月8日 13:44:10

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • getBoundingClientRect使用方法及兼容性处理

    这次给大家带来getBoundingClientRect使用方法及兼容性处理,getBoundingClientRect使用方法及兼容性处理的注意事项有哪些,下面就是实战案例,一起来看一下。 getBoundingClientRect的作用…

    编程技术 2025年3月8日
    200
  • React中组件的抽象使用方法

    这次给大家带来React中组件的抽象使用方法,React中组件的抽象使用注意事项有哪些,下面就是实战案例,一起来看一下。 mixin mixin的特性广泛存在于各个面向对象语言中,在ruby中,include关键词就是mixin,是将一个模…

    编程技术 2025年3月8日
    200
  • Vue组件通信Bus使用方法

    这次给大家带来Vue组件通信Bus使用方法,Vue组件通信Bus使用的注意事项有哪些,下面就是实战案例,一起来看一下。 在vue2.0中 $dispatch 和 $broadcast 已经被弃用。官方文档中给出的解释是: 因为基于组件树结构…

    编程技术 2025年3月8日
    200
  • JSONAPI在PHP中的使用方法

    这次给大家带来JSONAPI在PHP中的使用方法,JSONAPI在PHP中使用的注意事项有哪些,下面就是实战案例,一起来看一下。 现在服务端程序员的主要工作已经不再是套模版,而是编写基于 JSON 的 API 接口。可惜大家编写接口的风格往…

    编程技术 2025年3月8日
    200
  • vue mixins与extends的使用方法

    这次给大家带来vue mixins与extends的使用方法,vue mixins与extends使用的注意事项有哪些,下面就是实战案例,一起来看一下。 vue提供了mixins、extends配置项,最近使用中发现很好用。 混合mixin…

    编程技术 2025年3月8日
    200
  • Angular4输入与输出怎么使用

    这次给大家带来Angular4输入与输出怎么使用,使用Angular4输入与输出的注意事项有哪些,下面就是实战案例,一起来看一下。 Angular4输入属性 输入属性通常用于父组件向子组件传递信息 举个栗子:我们在父组件向子组件传递股票代码…

    编程技术 2025年3月8日
    200
  • 实现完整的Angular4 FormText组件需要哪些步奏

    这次给大家带来实现完整的Angular4 FormText组件需要哪些步奏,实现完整Angular4 FormText组件的注意事项有哪些,下面就是实战案例,一起来看一下。 本文主要介绍了如何编写一个完整的Angular4 FormText…

    编程技术 2025年3月8日
    200
  • vue父子组件通信使用方法

    这次给大家带来vue父子组件通信使用方法,使用vue父子组件通信的注意事项有哪些,下面就是实战案例,一起来看一下。 组件父子间通信之综合练习 {{msg}} // 创建父组件 Vue.component(“chat-room”,{ //da…

    编程技术 2025年3月8日
    200
  • Vue.js移动端组件库使用方法

    这次给大家带来Vue.js移动端组件库使用方法,Vue.js移动端组件库使用的注意事项有哪些,下面就是实战案例,一起来看一下。 Mint UI 包含丰富的 css 和 JS 组件,能够满足日常的移动端开发需要。通过它,可以快速构建出风格统一…

    编程技术 2025年3月8日
    200
  • vue组件生命周期使用方法

    这次给大家带来vue组件生命周期使用方法,vue组件生命周期使用的注意事项有哪些,下面就是实战案例,一起来看一下。 分为4个阶段: create/mount/update/destroy 每一个阶段都对应着有自己的处理函数 create: …

    编程技术 2025年3月8日
    200

发表回复

登录后才能评论