如何在Angular 4中动态创建具有动态Id的div
如何在Angular 4中动态创建具有动态Id的div
我正在尝试使用TypeScript添加带有id的div,但是没有成功分配。我只得到了一个div。
app.component.html
app.component.ts
import { Component } from '@angular/core'; import { Http } from '@angular/http'; import * as shape from 'd3-shape'; import { ElementRef } from '@angular/core'; declare var $: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { ngOnInit() { this.addDiv() } addDiv(){ this.htmlToAdd = '我的div'; } }
问题的原因是要在Angular 4中动态创建带有动态ID的div元素。解决方法是使用DomSanitizer来绕过安全性并将HTML内容赋值给trustedHtml变量。在组件中,使用ngOnInit来调用addDiv方法,该方法将带有动态ID的div元素的HTML内容赋值给trustedHtml变量。在HTML模板中,使用[innerHTML]绑定trustedHtml变量来动态创建div元素。
以下是解决方法的完整代码:
在组件中:
import { Component, OnInit } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit { trustedHtml: SafeHtml; constructor(public s: DomSanitizer) {} ngOnInit() { this.addDiv(); } public addDiv() { this.trustedHtml = this.s.bypassSecurityTrustHtml("my div"); } }
在HTML模板中:
通过以上方法,我们可以在Angular 4中动态创建带有动态ID的div元素。