16

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>
1
  • Please reproduce it. It works well for me Commented Nov 27, 2017 at 6:45

3 Answers 3

11

You can use it in directly template-

[ngStyle]="{'width.px': 200}"

or

dimensions = {'width.px': 200};
<div *ngIf="ready" class="card" [ngStyle]="dimensions">
</div
Sign up to request clarification or add additional context in comments.

1 Comment

for angular 15 use [style] instead of [ngStyle]
2

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'}"

1 Comment

Function call from template can lead to performance issues on large scale UIs
2

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

1 Comment

This seems to be necessary only if you have to use "!important". It's was made my code not work, thank you for the link ! I was going crazy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.