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?
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.
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>
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>";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With