单击按钮时,应克隆类别为emails
的元素。
HTML:
<form id="add-user">
<div class="email-container">
<div class="emails">
<mat-form-field class="email full-width">
<input matInput class="email-field" type="email" required placeholder="E-Mail">
</mat-form-field>
</div>
</div>
<i class="material-icons icon" id="addEmailField" (click)="clone()">add_box</i>
</form>
TS:
public clone(): void {
const clone = document.querySelector('.emails').cloneNode(true); // clone the selector .emails
document.querySelector('.email-container').appendChild(clone); // append it to .email-container
}
克隆部分有效,但是问题是克隆元素的占位符。如果我在文本字段中输入内容,它将不会消失。
这是我键入克隆元素时的外观:
我在做什么错? 运行并对其进行here测试。
答案 0 :(得分:1)
cloneNode()
克隆DOM-它不克隆Angular对象。您必须以“ Angular”方式克隆Angular组件。看到这篇文章:https://stackoverflow.com/a/41921531/9226213。
答案 1 :(得分:1)
使用ng-template
创建模板可以解决此问题。每当单击按钮时显示模板,并在页面加载ngOnInit()
时显示模板。
HTML:
<form id="add-user">
<ng-template #email>
<mat-form-field class="email full-width">
<input matInput class="email-field" type="email" required placeholder="E-Mail">
</mat-form-field>
</ng-template>
<div #furtherEmails></div>
</form>
<i class="material-icons icon" id="addEmailField" (click)="clone()">add_box</i>
TS:
@ViewChild('email') email;
@ViewChild('furtherEmails', {read: ViewContainerRef}) furtherEmails;
public clone(): void {
this.furtherEmails.createEmbeddedView(this.email);
}
ngOnInit() {
this.clone();
}
答案 2 :(得分:0)
您是否已在styles.css中导入了材质主题?
@import '@angular/material/prebuilt-themes/deeppurple-amber.css';