Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - How to access and replace innerHTML from a directive

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

This is what I have tried so far,

linkify.directive.ts

  constructor(private elementRef: ElementRef, private renderer: Renderer2) { 
      let elementText = this.elementRef.nativeElement.innerHTML;
      // elementText = '@user mentioned you';
      console.log(`Element Text: ${elementText}`);
      this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', this.stylize(elementText));
  }

and I'm using it like this

<p linkify> Hey @user check this out! </p>

While debugging I have made the following observations,

  • this.elementRef.nativeElement.innerHTML always has an empty string.
  • this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', 'something'); is appending something to the beginning of the element's text instead of replacing.

Question 1: How to access the innerHTML of an element?

Question 2: How to set the innerHTML of an element from a directive?

Stackblitz demonstrating the problem

I tried the documentation for Renderer2, but it's of no help for me.

like image 817
cyberpirate92 Avatar asked Jan 25 '18 20:01

cyberpirate92


1 Answers

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

like image 125
cyberpirate92 Avatar answered Nov 03 '22 20:11

cyberpirate92