0

I have created a pipe to format the XML string that I get from a server as a pretty printing.

import { Pipe, PipeTransform } from '@angular/core';
import * as jQuery from 'jquery';
import { escape } from 'querystring';
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) { }

  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;
  }
}

the string that I have is shown in the following div:

<tr *ngFor="let message of messages; let i = index;">
    <td *ngIf="i == _rowToShow" >{{message.xmlString | formatXml}}</td>
</tr>

_rowToShow is just a variable to limit the rows to show to an specific one and it works so it can not be the problem

so basically what I think that it is happening is that I am calling correctly to the pipe formatXml and I get the correct value of the string, but it is not a trusting HTML so it does not show it properly (it shows only the original XML).

I have read that to solve this problem in Angular 1.2 was just needed to use $sce.trustAsHtml but I do not really know how to do it.

https://odetocode.com/blogs/scott/archive/2014/09/10/a-journey-with-trusted-html-in-angularjs.aspx

Update

At the end what I get is

SafeValue must use [property]=binding:

plus my XML

Any body know what can be the problem?

bellotas
  • 2,349
  • 8
  • 29
  • 60

0 Answers0