簡體   English   中英

Angular2將HTML添加到動態元素

[英]Angular2 add HTML to dynamic elements

我有這個代碼:

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);      
    }

}

Angular2中有沒有辦法將HTML添加到.dynamically_created_div 因為上面只添加了組件的HTML結尾。

我也嘗試過:

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>'] );
    }

}

但它不起作用,因為@ViewChild指令必須在函數之外,我不能再控制它了

我也嘗試過這樣:

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

我無法做到,因為我的內容是動態的,並且使用了唯一的ID,我無法動態使用[innerHtml](它只適用於我第一次放入模板中的內容,然后任何其他更改的內容都不能再使用innerHtml了。

我檢查了Angular2:在DOM中插入一個動態組件作為容器的子項,但是存在同樣的問題,占位符不是動態的

更新:

我的代碼有點復雜:

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>

我試圖只使用ngFor但現在我得到了

Cannot set property 'cases' of undefined

這種方法有什么問題?

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);
    }

}

模板:

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

您可以使用ngfor並在其中創建元素,並使用索引創建不同的ID和名稱。 我做這樣的事情我不知道你是否想要做同樣的事情但這是我的代碼,動態創建一些輸入並添加或訪問他們的值

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM