繁体   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