在Angular 7中,可以使用cloneNode方法来克隆元素。以下是一个包含代码示例的解决方法:
在HTML模板中,定义一个元素:
Original Element
在组件中,使用ViewChild装饰器获取对原始元素的引用,并在响应的方法中进行克隆:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `
Original Element
`
})
export class ExampleComponent implements AfterViewInit {
@ViewChild('originalElement', { static: false }) originalElement: ElementRef;
@ViewChild('clonedElement', { static: false }) clonedElement: ElementRef;
cloneElement() {
const original = this.originalElement.nativeElement;
const clone = original.cloneNode(true);
this.clonedElement.nativeElement.appendChild(clone);
}
ngAfterViewInit() {
// Access the original element here if needed
const original = this.originalElement.nativeElement;
console.log(original);
}
}
在上述示例中,我们首先使用ViewChild装饰器获取对原始元素和克隆元素的引用。然后,我们为按钮添加了一个点击事件处理程序cloneElement(),该方法在点击按钮时将原始元素克隆并将其附加到克隆元素中。在ngAfterViewInit生命周期钩子中,我们还可以访问原始元素的引用,以便在需要时进行其他操作。