龙空技术网

利用Angular elementRef 实现一键复制功能

博读代码 72

前言:

当前大家对“angular绑定按钮跳转页面”可能比较注意,姐妹们都需要分析一些“angular绑定按钮跳转页面”的相关资讯。那么小编也在网摘上收集了一些关于“angular绑定按钮跳转页面””的相关知识,希望大家能喜欢,兄弟们快快来了解一下吧!

前言

由于在之前有个项目需要实现一键复制功能,一开始大多数都会想着自己用 js 手写封着。后来发现 Angular 有个机制,可以很简单地实现一键复制功能。

背景

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 worker 有兴趣的可以去阅读了解下支持的类和方法。

通过 ElementRef 我们就可以封装不同平台下视图层中的 native 元素 (在浏览器环境中,native 元素通常是指 DOM 元素),最后借助于 Angular 提供的强大的依赖注入特性,我们就可以轻松地访问到 native 元素。

首先,对比下之前写的

<p id="copyText" title="内容" (click)="isShow = true" *ngIf="!isShow">内容</p>        <textarea id="copyUp" (click)="isShow = false" *ngIf="isShow"> 内容</textarea>        <span (click)="copyUrl(isShow ? 'copyUp' : 'copyText')">复制</span>
copyUrl(type) {        let cont;        if (type === 'copyUp') {            $('#copyUp').select();            document.execCommand('copy');            cont = $('#copyUp').text();        } else {            $('#copyText').select();            document.execCommand('copy');            cont = $('#copyText').text();        }        let flag = this.copyText(cont);        flag ? LayerFunc.successLayer('复制成功!') : LayerFunc.errorLayer('复制失败!');    }    copyText(text) {        let textarea = document.createElement('input'); // 创建input对象        let currentFocus = document.activeElement; // 当前获得焦点的元素        document.body.appendChild(textarea); // 添加元素        textarea.value = text;        textarea.focus();        let flag;        if (textarea.setSelectionRange) textarea.setSelectionRange(0, textarea.value.length);        // 获取光标起始位置到结束位置        else textarea.select();        try {            flag = document.execCommand('copy'); // 执行复制        } catch (eo) {            flag = false;        }        document.body.removeChild(textarea); // 删除元素        return flag;    }}

利用添加一个 textarea 标签,通过 textarea 的 select 方法选中文本,然后再通过浏览器提供的 copy 命令,将 textarea 中的内容复制下来的方法。

利用ElementRef实现的一键复制

首先,注册ElementRef

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

然后,在constructor引入

 constructor(        private elementRef: ElementRef    ) {}
<input type="text" id="copy_value" vlaue="">内容<button (click)="copyText(内容值)">复制</button>
   copyText(text: string) {      const input = this.elementRef.nativeElement.querySelector('#copy_value');      input.value = text;      input.select();      document.execCommand('copy');      LayerFunc.successLayer('复制成功');    }

总结

在利用 Angular 开发的时候可以多学习 Angular 机制,会发现在一些功能的开发上,用好了它自身封好的方法,其实有很多地方可以避免不必要代码,有时写原生的时候可能会过于繁杂,有些方法缺可以很简单的去帮你实现,减少了代码量。

下期跟大家分享node调试工具的使用,敬请期待~

欢迎各位关注、留言,大家的支持就是我的动力!

标签: #angular绑定按钮跳转页面