Reputation: 2316
In my angular 5 app, [ngStyle] is not expanding to style attribute. I only see ng-reflect-ng-style. This used to work before. Did something change in the recent updates to Angular or Angular-cli?
This is template:
<div *ngIf="ready" class="card" [ngStyle]="dimensions">
</div
This is the generated HTML:
<div _ngcontent-c6="" class="card ng-tns-c6-1" ng-reflect-ng-style="[object Object]">
</div>
Expected, with dimensions = {width: '240px'}:
<div _ngcontent-c6="" class="card ng-tns-c6-1" ng-reflect-ng-style="[object Object]" style="width:240px">
</div>
Upvotes: 16
Views: 23925
Reputation: 8491
As of today & with Angular > 11, you have to sanitize such information like the following
<div [attr.style]="dimensions | safeStyle"> </div>
Were safeStyle
is
@Pipe({ name: 'safeStyle' })
export class SafeStylePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(value) {
return this.sanitizer.bypassSecurityTrustStyle(value)
}
}
Found the solution on this thread
Upvotes: 2
Reputation: 14669
You can try as below as well:
<div *ngIf="ready" class="card" [ngStyle]="setStyles()">
</div>
public setStyles(): any {
let styles = {
'width': '200px'
};
return styles;
}
OR
[ngStyle]="{'width': '200px'}"
Upvotes: 2
Reputation: 1040
You can use it in directly template-
[ngStyle]="{'width.px': 200}"
or
dimensions = {'width.px': 200};
<div *ngIf="ready" class="card" [ngStyle]="dimensions">
</div
Upvotes: 11