Use Angular elementRef to realize one-click copy function

Preface

Since there was a project that needed to implement the one-click copy function before, most of them would think about sealing them with js handwriting. Later, it was discovered that Angular has a mechanism that can easily realize the one-click copy function.

background

Angular's slogan is-"One framework, multiple platforms. Applicable to mobile phones and desktops (One framework.Mobile & desktop.)", that is, Angular supports the development of cross-platform applications, such as: Web applications, mobile Web applications, native Mobile applications and native desktop applications, etc. In order to be able to support cross-platform, Angular encapsulates the differences between different platforms through an abstraction layer and unifies the API interface. For example, the abstract class Renderer and the abstract class RootRenderer are defined. In addition, the following reference types are defined: ElementRef, TemplateRef, ViewRef, ComponentRef, ViewContainerRef, etc. Let's analyze the ElementRef class:

ElementRef role

Direct manipulation of the DOM at the application layer will result in a strong coupling between the application layer and the rendering layer, causing our application to not run in different environments, such as web workers, because in the web worker environment, the DOM cannot be directly manipulated. Those interested in web workers can read about the supported classes and methods. Through ElementRef, we can encapsulate the native elements in the view layer under different platforms (in the browser environment, native elements usually refer to DOM elements), and finally with the help of the powerful dependency injection feature provided by Angular, we can easily access native element.

First of all, compare what I wrote before

<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;
    }
}

Add a textarea tag, select the text through the select method of the textarea, and then copy the content in the textarea through the copy command provided by the browser.

Let's take a look at the one-click copy implemented with ElementRef

First go to register ElementRef

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

Then introduce in the 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('复制成功');
    }

In summary

, you can learn more about the angular mechanism when developing with angular. You will find that in the development of some functions, you can use its own sealed method. In fact, there are many places to avoid unnecessary code. Sometimes it may be too much when writing native Complex, some methods can be easily implemented for you, reducing the amount of code.

Guess you like

Origin blog.51cto.com/15024210/2582588