Angular - How to access and replace innerHTML from a directive

前端 未结 1 1819
忘掉有多难
忘掉有多难 2021-01-13 07:10

I am trying to create a directive that modifies the element\'s innerHTML by adding links to those substrings which start with @ symbol.

Thi

相关标签:
1条回答
  • 2021-01-13 08:02

    As @bryan60 suggested, The ideal way to do this is to create a pipe instead of a directive.

    This is the pipe I ended up creating,

    linkify.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser';
    
    @Pipe({
      name: 'linkify'
    })
    export class LinkifyPipe implements PipeTransform {
    
      constructor(private _domSanitizer: DomSanitizer) {}
    
      transform(value: any, args?: any): any {
        return this._domSanitizer.bypassSecurityTrustHtml(this.stylize(value));
      }
    
      private stylize(text: string): string {
        let stylizedText: string = '';
        if (text && text.length > 0) {
          for (let t of text.split(" ")) {
            if (t.startsWith("@") && t.length>1)
              stylizedText += `<a href="#${t.substring(1)}">${t}</a> `;
            else
              stylizedText += t + " ";
          }
          return stylizedText;
        }
        else return text;
      }
    
    }
    

    Usage:

    <p [innerHTML]="sample | linkify"></p>
    

    Demo Stackblitz

    0 讨论(0)
提交回复
热议问题