设置为SafeHTML - Angular 2

时间:2018-01-26 13:42:18

标签: javascript angular

我有div id是“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文件调用我的管道,我得到了答案。问题是当我在div上打印时,字符串保持不变(没有格式)。

我读过我需要:

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

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

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

1 个答案:

答案 0 :(得分:1)

<强>更新

最后两行应为

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,并且可能会出现。