Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - Angular2 add HTML to dynamic elements

I have this code:

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

@Component({
    selector: 'my-app',
    template: '<button (click)="runR()">Run</button>
<div class="testme">
    <div class="somediv">
        <div class="dynamically_created_div unique_identifier"></div>
        <div class="dynamically_created_div unique_identifier"></div>
        <div class="dynamically_created_div unique_identifier"></div>
    </div>
</div>',
})

export class AppComponent{
    hostEl: any;

    constructor(
        private el:ElementRef,
        private renderer:Renderer2,
    )  {
        this.hostEl = el.nativeElement;
    }

    runR(){
        let change_this;
        change_this= this.renderer.createElement('span');
        this.renderer.addClass(change_this, 'change_this');
        this.renderer.appendChild(this.hostEl, change_this);      
    }

}

Is there any way in Angular2 to add HTML to the .dynamically_created_div? Because the above only adds to the end of the HTML of the component.

I also tried with:

import { Component, ElementRef, ViewChild, Renderer, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<button (click)="runR()">Run</button>
<div class="testme">
    <div class="somediv">
        <div class="dynamically_created_div">

        </div>
    </div>
</div>
  `,
})
export class AppComponent {
  constructor(private renderer:Renderer) {}

    runR() {
        @ViewChild('dynamically_created_div') d1:ElementRef;
        this.renderer.invokeElementMethod(this.d1.nativeElement, 'insertAdjacentHTML', ['beforeend', '<div class="new_div">new_div</div>'] );
    }

}

But it's not working because the @ViewChild directive must be outside the function and I can't have control over it anymore

I also tried like this:

<div class="dynamically_created_div" [innerHtml]="newHTML"></div>
this.newHTML = '<div class="new_div">new_div</div>';

Thing I cannot do because my content is dynamic and uses unique IDs and I cannot use [innerHtml] dynamically ( it only works for what I put in themplate for the first time, then anything else that changes can't use innerHtml anymore.

I checked Angular2: Insert a dynamic component as child of a container in the DOM but there is the same problem, the placeholders aren't dynamic

UPDATE:

My code is a little bit more complex:

TS:

import { AfterContentInit, Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
import { NgForm, FormsModule, ReactiveFormsModule, FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { SFService } from '../services/sf.service';
import { Injectable, Pipe, PipeTransform } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    providers: [ SFService ],
})

export class AppComponent implements OnInit {
    constructor(
        private sfservice: SFService,
    ) {}

    ngOnInit(){
        this.sfservice.getMembers().subscribe(members => {
            this.members = members.members;
        });
    }


    members: Member[];
    member_selector: Member[];

    member_each: Member;
    member_selector_each: Member[];
    cases: Case;

    runR(){

        this.members.forEach(member_each => {
            this.member_selector.forEach(member_selector_each => {
                if(member_each.Id === member_selector_each.Id){
                    console.log(member_selector_each.Id);
                    this.sfservice.getCaseHistory(member_selector_each.Id, "2017-04-25T00:00:00", "2017-04-28T23:59:59").subscribe(cases => {

                        this.member_each['cases'] = cases;
                        console.log(this.member_each);
                    });
                }
            })
        })
    }
}

HTML:

<form #myForm="ngForm" novalidate>
    <select name="member_selector_name" [(ngModel)]="member_selector" multiple ng-model="selectedValues" style="height:200px;">
        <option *ngFor="let member of members" [ngValue]="member">{{member.Name}}</option>
    </select>
    <button (click)="runR()">Run</button>
</form>

<div id="results">
    <div *ngFor="let mem of members" class="member-card-{{mem.Id}}">
        <div class="card-container">
             <div *ngFor="let case of mem.Cases" class="case-card" id="{{case.Id}}">{{case.Number}}
             </div>
        </div>
    </div>
</div>

I was trying to use only ngFor but now I get

Cannot set property 'cases' of undefined
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...