键入时占位符不会消失

时间:2018-07-23 12:28:58

标签: javascript typescript angular-material angular6

单击按钮时,应克隆类别为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
}

克隆部分有效,但是问题是克隆元素的占位符。如果我在文本字段中输入内容,它将不会消失。

这是我键入克隆元素时的外观:

enter image description here

我在做什么错? 运行并对其进行here测试。

3 个答案:

答案 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';