簡體   English   中英

根據Angular中的單擊動態添加dom元素

[英]Dynamically adding dom elements based on click in Angular

我有兩個按鈕,分別為ImageText 基於這些按鈕的單擊,我想向dom中動態添加一個元素,即TextArea或ImageArea。

因為我的HTML代碼很長,所以我不能使用nativeElement.append(var);

我現在應該使用哪種方法將元素動態添加到dom。

正確的答案取決於應用程序的體系結構以及您的實際需求。 Angular提供了許多向DOM添加元素的方法。 最簡單且可能解決您問題的方法是僅使用*ngIf ,例如:

// component.ts

showImage: boolean = false;

// component.html

<img src="img.jpg" *ngIf="showImage">
<button (click)="showImage=true">Show image</button>

如果要向DOM中添加幾個元素,可以使用*ngFor

// component.ts

images: any[] = [];

addImage() {
  this.images.push(this.images.length+1);
}

removeImage() {
  this.images.pop();
}

// component.html

<img src="img.jpg" *ngFor="let img of images">
<button (click)="addImage()">Show an image more</button>
<button (click)="removeImage()">Show an image less</button>

編輯:

// component.ts

imagesAndTextarea: string[] = [];

addImg() {
  this.imagesAndTextarea.push('img');
}

addTextarea() {
  if (this.iamgesAndTexarea.filter(x => x === 'textarea').length >= 12) return;
  this.imagesAndTextarea.push('textarea');
}

// template.html

<ng-container *ngFor="let el of imagesAndTextarea">
  <textarea .... *ngIf="el === 'textarea'">
  <img .... *ngIf="el === 'img'">
</ng-container>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM