Angular2 add HTML to dynamic elements

后端 未结 2 1960
暖寄归人
暖寄归人 2020-12-10 13:23

I have this code:

import { Component, ElementRef, Renderer2 } from \'@angular/core\';

@Component({
    selector: \'my-app\',
    template: \'
相关标签:
2条回答
  • 2020-12-10 13:46

    What's the problem with this approach?

    export class AppComponent{
        @ViewChild('d1') d1:ElementRef;
        @ViewChild('d2') d2:ElementRef;
        @ViewChild('d3') d3:ElementRef;
    
        constructor(private renderer:Renderer2)  {    }
    
        runR(){
            let change_this;
            change_this= this.renderer.createElement('span');
            this.renderer.addClass(change_this, 'change_this');
            this.renderer.appendChild(this.d1, change_this);
        }
    
    }
    

    Template:

    <div class="dynamically_created_div unique_identifier" #d1></div>
    <div class="dynamically_created_div unique_identifier" #d2></div>
    <div class="dynamically_created_div unique_identifier" #d3></div>
    
    0 讨论(0)
  • 2020-12-10 13:50

    you can use ngfor and create you elements inside it and using index you can create different ids and names. I do something like this i dont know if you want to do the same but here's my code to create some input's dynamically and add or access their values

    <div *ngFor="let comp of templateVals | async;let i=index">
    
      <md-input-container class="example-90" *ngIf="comp.type=='code'">
        <textarea rows="4"  mdInput  name="desc{{i}}" [(ngModel)]="comp.data" placeholder="Description"></textarea>
      </md-input-container>
      <md-input-container class="example-90" *ngIf="comp.type=='text'">
        <textarea rows="4"  mdInput name="text{{i}}" [(ngModel)]="comp.data" placeholder="Text"></textarea>
      </md-input-container>
      <md-input-container class="example-90" *ngIf="comp.type=='title'">
        <input mdInput name="title{{i}}" [(ngModel)]="comp.data" placeholder="Title">
      </md-input-container>
      <span class="example-90" *ngIf="comp.type=='upload'">
    
        <input-file *ngIf="!comp.data" [acceptId]="comp.id"  (onFileSelect)="addedFileInfo($event)"></input-file>
      <span *ngIf="comp.data">{{comp.data}}</span>
    
      </span>
      <span class="example-10">
      <button md-mini-fab (click)="removeThis(comp)"><md-icon>remove circle</md-icon></button>
        </span>
    </div>

    0 讨论(0)
提交回复
热议问题