Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse HTML string in Angular 2 and extract and update values

Tags:

angular

svg

I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

Now displaying the string is easily done with the following code:

<div [innerHTML]="displayString"></div>

My input string has some <span> elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

Example: let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

Are operations like these even possible in Angular 2?

like image 969
hY8vVpf3tyR57Xib Avatar asked Jun 03 '17 21:06

hY8vVpf3tyR57Xib


3 Answers

You can use DomSanitizer from platform-browser module

import {DomSanitizer} from '@angular/platform-browser';

Inject DomSanitizer in your component by initializing it in your constructor

  constructor(private domSanitizer: DomSanitizer)

use bypassSecurityTrustHtml() of DomSanitizer and pass your raw html content:

this.displayString= this.domSanitizer.bypassSecurityTrustHtml("<svg><text data-card-text>Value I want to update</text></svg>");

I hope this will solve your problem.

like image 62
Deepak Kumar Avatar answered Nov 12 '22 06:11

Deepak Kumar


You have to create one Shared Service in which all your global variables are defined like below. Your global variable is "displayString"

export interface SharedModel {
    displayString: string;
    dynamicValue: string;
}

@Injectable()
export class Shared {
    SharedComponent: SharedModel = {
           dynamicValue:'',
           displayString: '<svg><text data-card-text>'+this.SharedComponent.dynamicValue+'</text></svg>'
    };
}

Now access this service in your component where you need to set/get displayString as below.

import { Shared, SharedModel } from '../Shared';
export class MyComponent {
     public sharedData: SharedModel;
     constructor(public sharedResource: Shared)
     {
         this.sharedData = sharedResource.SharedComponent;
     }
}

Assign Value:(it may be in other component/service/APi in your case)

ngOnInit()
{
     this.sharedData.dynamicValue="My name is SANDIP PATEL"
}

Access/Get value in HTML:

<div [innerHTML]="sharedData.displayString"></div>
like image 9
Sandip - Frontend Developer Avatar answered Nov 12 '22 04:11

Sandip - Frontend Developer


In you component you can just define variable displayString as a public and then you can use it in html

public displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>";
like image 2
Giga Songulashvili Avatar answered Nov 12 '22 04:11

Giga Songulashvili