gpt4 book ai didi

Angular2 innerHTML 删除属性,使用 DomSanitizer 需要帮助

转载 作者:太空狗 更新时间:2023-10-29 17:57:09 38 4
gpt4 key购买 nike

我只需要在带有 id "main-wrapper" 的 div 中注入(inject) HTML,所以在我的 component.ts 中我使用了这段代码

    import { Component, OnInit, ElementRef,Renderer2,Inject } from '@angular/core';
import { Pipe } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

@Component({
selector: 'app-editsection',
templateUrl: './editsection.component.html',
styleUrls: ['./editsection.component.css']
})

export class EditsectionComponent implements OnInit {
...//some code

constructor(
@Inject(DOCUMENT) private document: any,
private route: ActivatedRoute,
private elRef: ElementRef,
private el: ElementRef,
private _sanitizer:DomSanitizer
) { }

ngOnInit() {
var strHTML = '<p>abc<p>';
this.document.getElementById("main-wrapper").innerHTML += this._sanitizer.bypassSecurityTrustHtml(strHTML);

...
}
}

当我运行代码时,它说:SafeValue 必须使用 [property]=binding:美国广播公司

(参见 http://g.co/ng/security#xss)

为什么我需要实现这个——因为当我注入(inject) innerHTML 时,我失去了一个属性 contenteditable="true"

在应用 innerHTML 之前,我的代码如下所示:

<h1 _ngcontent-c2 contenteditable="true">Hii<h2>

在应用 innerHTML 后它变成:

<h1 _ngcontent-c2>Hii<h2>

请帮我解决问题

最佳答案

按照 http://angularjs.blogspot.com.au/2016/04/5-rookie-mistakes-to-avoid-with-angular.html 中的建议,angular 背后的整个方法论都基于通过脚本(例如您拥有的脚本)减少 DOM 操作。 .

There are very few circumstances where manipulating the DOM directly is necessary. Angular 2 provides a set of powerful, high-level APIs like queries that one can use instead. Leveraging these APIs confers a few distinct advantages

...

When you manipulate the DOM manually, you miss out on these advantages and ultimately end up writing less expressive code.


所以不要使用这个:this.document.getElementById("main-wrapper").innerHTML +=

您应该使用模板引擎/结构指令,例如 Angular 中固有的 *ngFor *ngIf

// .html
<div class="main-wrapper"><p *ngIf="showabc">abc</p></div>
// .ts
var showabc: Boolean = true;

根据您的评论:

您正在从本地存储加载一堆 html。在这种情况下,您将不得不操作 DOM。理想情况下,我建议重新配置此架构以达到上述性能目的。

1,将 html 加载到 typescript 中......

public possibleHTML: Array; 
constructor(private sanitizer: DomSanitizer){}
ngOnInit(){
this.possibleHTML = loadContentFromLocalStorage();
this.possibleHTML = this.possibleHTML.map(value => this.sanitizer.bypassSecurityTrustHtml(value));
}

第二次插入 html。

<div class="main-wrapper">
<content *ngIf="possibleHTML">
<div *ngFor="let html of possibleHTML">
<div *ngIf="html.makevisible" [innerHtml]="html"></div>
</div>
</content>
</div>

缺点:css样式不生效,除非定义为全局样式表styles.css而不是editsection.component.css .

关于Angular2 innerHTML 删除属性,使用 DomSanitizer 需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44556633/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com