In Angular4, property binding on the view (.html) picks up the value from the logic file (.ts)
This works well in the code:
<img [src]="sourceValue">
This too works well in the code:
<button [disabled]="isDisabled">
Why does this not work?
<p [style]="paragraphStyle"> This is a paragraph.</p>
abc.component.ts
isDisabled:boolean = true;
sourceValue:string = "./assets/hermione.jpg";
paragraphStyle:string = "background:red; color:yellow";
I know the usage of ngStyles and ngClass, I simply want to ask why property binding is not working in the above case. It is finally --- just a simple "Inline CSS Styling" if value is taken from .ts file and added to the html snippet in front of 'style' property in paragraph.
It's because of security Measures:
@Angular docs
Angular defines the following security contexts:
binding to innerHtml.
URL is used for URL properties, such as
<a href>.
Resource URL is a URL that will be loaded and executed as code, for example, in
<script src>
.The Fix is to sanitize values beforehand using
bypassSecurityTrustStyle()
- Bypass security and trust the given value to be safe style value (CSS).Component:
HTML
NOTE:
Live Demo