gpt4 book ai didi

javascript - 设置为 SafeHTML - Angular 2

转载 作者:行者123 更新时间:2023-11-30 20:48:16 26 4
gpt4 key购买 nike

我有一个 divid 是“carID”。

我需要做这样的事情:

magic(){
//Safe Html is imported previously in the component
document.getElementById('carID'): SafeHtml
}

所以基本上我需要的是将我的 div 类型更改为 SafeHtml

管道

我有一个管道:

import { Pipe, PipeTransform } from '@angular/core';
import * as jQuery from 'jquery';
import { escape } from 'querystring';
import { TestExecutionComponent } from './test-execution/test-execution.component';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

//import * as angular from '../angular.js';
//CAMBIAR a string
@Pipe({
name: 'formatXml'
})
export class FormatXmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}

testExecutionComponent: TestExecutionComponent;

transform(xml: String): SafeHtml {
var formatted = '';
var reg = /(>)(<)(\/*)/g;
xml = xml.replace(reg, '$1\r\n$2$3');
var pad = 0;
jQuery.each(xml.split('\r\n'), function (index, node) {
var indent = 0;
if (node.match(/.+<\/\w[^>]*>$/)) {
indent = 0;
} else if (node.match(/^<\/\w/)) {
if (pad != 0) {
pad -= 1;
}
} else if (node.match(/^<\w[^>]*[^\/]>.*$/)) {
indent = 1;
} else {
indent = 0;
}

var padding = '';
for (var i = 0; i < pad; i++) {
padding += ' ';
}

formatted += padding + node + '\r\n';
pad += indent;
});

var escaped = formatted.replace(/&/g, '&amp;').replace(/</g, '<').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;').replace(/\n/g, '<br />');
// https://stackoverflow.com/questions/39240236/insert-xml-into-dom-in-angular-2
let safeEscaped = this.sanitized.bypassSecurityTrustHtml(escaped);

return safeEscaped;
//let safeEscaped = this.sanitized.bypassSecurityTrustHtml(escaped);

//return safeEscaped;
}
}

我在哪里使用 bypassSecurityTrustHtml 和字符串。

组件

  <div id="carDiv" class="table-responsive">
<table class="table table-bordred table-striped ">
<tbody *ngIf="cars">
<tr *ngFor="let car of cars; let i = index;">
<td *ngIf="i==_rowToShow" [innerHTML]="car.ID| formatXml"></td>
</tr>
</tbody>
</table>
</div>

我的代码运行正常。我从 HTML 文件调用我的 Pipe,然后我得到了答案。问题是,当我在 div 上打印它时,字符串保持不变(无格式)。

我已阅读我需要:

  • 首先:在字符串上使用bypassSecurityTrustHtml
  • 第二:在 SafeHtml 上打印

我正在检查的帖子如下:Here

我已经迈出了第一步,所以我想我现在需要的是为 Div 使用 SafeHtml。我该怎么做?

最佳答案

更新

最后两行应该是

let safeEscaped = this.sanitized.bypassSecurityTrustHtml(escaped);

return safeEscaped;

原创

这可能会做你想做的事

class MyComponent {
constructor(private sanitizer:DomSanitizer){}

magic(){
var safe = this.sanitizer.bypassSecurityTrustHtml(document.getElementById('carID').outerHTML);
}
}

但是根据获取的元素包含的内容,这可能是具有安全性的 Harakiri。

关于javascript - 设置为 SafeHTML - Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48462512/

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