简体   繁体   English

根据Angular中的单击动态添加dom元素

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

I have two buttons as Image and Text . 我有两个按钮,分别为ImageText based on click of these buttons I want to dynamically add an element to the dom ie either TextArea or ImageArea. 基于这些按钮的单击,我想向dom中动态添加一个元素,即TextArea或ImageArea。

Since my HTML code is very lengthy I cant use nativeElement.append(var); 因为我的HTML代码很长,所以我不能使用nativeElement.append(var);

What approach should I use now to append my elements dynamically to the dom. 我现在应该使用哪种方法将元素动态添加到dom。

a correct answer depends on the architecture of your application and what you exactly need. 正确的答案取决于应用程序的体系结构以及您的实际需求。 Angular provides many ways to add elements to the DOM. Angular提供了许多向DOM添加元素的方法。 The easiest and what probably solve your problem, is to just use *ngIf , for example: 最简单且可能解决您问题的方法是仅使用*ngIf ,例如:

// component.ts

showImage: boolean = false;

// component.html

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

If you want to add several elements to DOM, you can use *ngFor : 如果要向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>

Edit: 编辑:

// 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