简体   繁体   中英

Dynamically adding dom elements based on click in Angular

I have two buttons as Image and Text . based on click of these buttons I want to dynamically add an element to the dom ie either TextArea or ImageArea.

Since my HTML code is very lengthy I cant use nativeElement.append(var);

What approach should I use now to append my elements dynamically to the 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. The easiest and what probably solve your problem, is to just use *ngIf , for example:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM