Angular - transform innerHtml using two pipes

5.7k Views Asked by At

Used two pipes to make an html markup, from my database, safer and shorter:

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(protected sanitizer: DomSanitizer) {}

     public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
        switch (type) {
                case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
                . . .
            }
      }
    }

and

@Pipe({
  name: 'summary'
})
export class SummaryPipe implements PipeTransform {

  transform(content: string, characterLimit: number): string {
    if (content.length <= characterLimit) {
      return content;
    } else {
      return `${content.substring(0, characterLimit)}...`;
    }
  }

}

Using it with one pipe it works:

<div [innerHtml]="blog.content | safe: 'html'"></div>

But with the second pipe it stops showing:

<div [innerHtml]="blog.content | safe: 'html' | summary:100"></div>

How can I fix it ?

2

There are 2 best solutions below

3
On BEST ANSWER

Your summary pipe is expecting a string, but your safe pipe return a SafeValue.

You should use the safe pipe last:

<div [innerHtml]="blog.content | summary:100 | safe: 'html'"></div>

This is the only way to get it working in this specific case because the summary pipe return a new unsafe string. It would get sanitized by innerHtml automatically if used last.

Since the bypassSecurityTrustHtml don't change the value at all, it's safe to call it last. If you do need to sanitize the string (remove html elements), just pass a string directly to innerHtml without any bypass method and it will be sanitized for you.

1
On
  <div [innerHtml]="(blog.content | safe: 'html') | summary:100"></div>

did you try doing this?