Reputation: 1
i have this kind of string
"<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sit amet vestibulum eros, ac aliquam magna. Interdum et malesuada fames ac ante ipsum primis in faucibus. In ante urna, dictum sed porta ut, consectetur eu felis. Pellentesque eleifend egestas augue, iaculis ultricies nulla volutpat at. Vivamus sagittis est eu rutrum blandit"
which includes style attributes i want to bind it to my html but whatever i try i always lose some styles like the first one
("<div style="text-align: center;" )
any idea how to put this into my html without losing any styles ? thank you
Upvotes: 0
Views: 597
Reputation: 798
Well i do assume you've used [innerHtml]
directive on your HTML element like this:
// Your *.html template
<p [innerHTML]="myUnsafeHtmlString"></p>
// Your *.component.ts controller file
myUnsafeHtmlString: string = `<div style="text-align: center;">
<b style="color: rgb(122, 122, 122); font-family: 'Open Sans', Arial, sans-serif; text-align: justify;">Lorem ipsum...</b></div>`;
In that case Angular will block some HTML attributes because of safety reasons. You have info about this inside your browser developer tools -> console tab.
More about DomSanitizer in Angular - https://angular.io/api/platform-browser/DomSanitizer
To achieve "unsafe" html in your templates you need to explicitly call it thru DomSanitizer. In my example I've used @Pipe to achieve this, however your can also use it from your components controller.
// Your *.html template
<p [innerHTML]="myUnsafeHtmlString | safeHtml"></p>
// Your *.pipe.ts
@Pipe({ name: 'safeHtml' })
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
// Your *.component.ts controller file
myUnsafeHtmlString: string = `<div style="text-align: center;">
<b style="color: rgb(122, 122, 122); font-family: 'Open Sans', Arial, sans-serif; text-align: justify;">Lorem ipsum...</b></div>`;
Full stackblitz example:
https://stackblitz.com/edit/angular-ivy-yxcwjb?file=src%2Fapp%2Fapp.component.html
Upvotes: 0