Angular2 给动态元素添加 HTML [英] Angular2 add HTML to dynamic elements

查看:49
本文介绍了Angular2 给动态元素添加 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

import { Component, ElementRef, Renderer2 } from '@angular/core';@成分({选择器:'我的应用',模板:'<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>

',})导出类 AppComponent{hostEl:任何;构造函数(私人 el:ElementRef,私人渲染器:Renderer2,){this.hostEl = el.nativeElement;}运行R(){让 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';@成分({选择器:'我的应用',模板:`<button (click)="runR()">Run</button><div class="testme"><div class="somediv"><div class="dynamically_created_div">

`,})导出类 AppComponent {构造函数(私有渲染器:渲染器){}运行R(){@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';从'../services/sf.service'导入{SFService};import { Injectable, Pipe, PipeTransform } from '@angular/core';@成分({选择器:'我的应用',templateUrl: './app.component.html',提供者:[ SFService ],})导出类 AppComponent 实现 OnInit {构造函数(私人 sfservice: SFService,) {}ngOnInit(){this.sfservice.getMembers().subscribe(members => {this.members = members.members;});}成员:成员[];成员选择器:成员[];member_each:成员;member_selector_each: 成员[];案例:案例;运行R(){this.members.forEach(member_each => {this.member_selector.forEach(member_selector_each => {if(member_each.Id === member_selector_each.Id){控制台日志(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'] = 案例;console.log(this.member_each);});}})})}}

HTML:

<select name="member_selector_name" [(ngModel)]="member_selector" 多个 ng-model="selectedValues" style="height:200px;"><option *ngFor="let member of members" [ngValue]="member">{{member.Name}}</option></选择><button (click)="runR()">运行</button></表单><div id="结果"><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}}

我试图只使用 ngFor 但现在我得到了

无法设置未定义的属性cases"

解决方案

这种方法有什么问题?

导出类 AppComponent{@ViewChild('d1') d1:ElementRef;@ViewChild('d2') d2:ElementRef;@ViewChild('d3') d3:ElementRef;构造函数(私有渲染器:Renderer2){}运行R(){让 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>

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

解决方案

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>

这篇关于Angular2 给动态元素添加 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆