Home > Software engineering >  How to get id of a div from safeHtml?
How to get id of a div from safeHtml?

Time:10-05

I have one html saved in database, which i get from API call. this is the response

ex.

htmlText = <div class="dragBlock"> 
                <div id="Name">Test</div>
                 <div id="Age">23</div>
           </div>

In view i am showing this as

<div class="preview">
    <div [innerHtml] = "htmlText | safeHtml"> </div>
 </div>

this works fine, but i want to change inner Html of id Name and Age

In ts file I am doing this

document.getElementById('Name').innerHtml = 'UserName';

but this is not working, Can we do this in Angular? If yes how?

CodePudding user response:

You need use it like this:

document.getElementById('Name').innerHTML = 'UserName';

See this Stackblitz: https://stackblitz.com/edit/angular-sbxeon?file=src/app/app.component.ts

CodePudding user response:

You can use a pipe to manipulate the HTML.

  import { Pipe, PipeTransform } from '@angular/core';
  import { DomSanitizer } from '@angular/platform-browser';
  
  @Pipe({
    name: 'modify'
  })
  export class ModifyPipe implements PipeTransform {
  
    constructor(private _domSanitizer: DomSanitizer) {}
  
    transform(html: string, args?: any): any {
      return this._domSanitizer.bypassSecurityTrustHtml(this.modify(html));
    }
  
    private modify(html: string): string {
      // Do your manipulation here by replacing with regex
      return string;
    }
  
  }


  <p [innerHTML]="htmlText | modify"></p>
  • Related