Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2.0 and ng-style

I am building an Angular 2.0 component and I want to control it's style dynamically (using ng-style). After a quick view on Angular 2's docs i tried this:

<div class="theme-preview" ng-style="{'font-size': fontSize}">
  {{fontSize}}
</div>

And saw that the size is actually printed inside the div but did not affected the style. fontSize is one of component's property bindings', meaning the component gets it from its parent like this:

<my-component [font-size]="size" />

While inside the component I have:

@Component({
  selector: 'XXX',
  properties: ['fontSize']
})

Am I missing something here?

like image 821
Yaniv Efraim Avatar asked Aug 30 '15 19:08

Yaniv Efraim


People also ask

Can we use NgClass and ngStyle together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

What is the difference between NgClass and ngStyle?

ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute.


2 Answers

Update

People still reach this answer, so I've updated the plnkr to beta.1. Two things have changed so far

  • NgStyle is no longer necessary to be explicitly added in directives property. It's part of the common directives that are added by default.
  • The syntax has changed, now it must be camel case.

Example

@Component({
  selector : 'my-cmp',
  template : `
    <div class="theme-preview" [ngStyle]="{'font-size': fontSize+'px'}">
   {{fontSize}}
  </div>`
})
class MyCmp {
  @Input('font-size') fontSize;
}

@Component({ 
  selector: 'my-app',
  directives: [MyCmp],
  template: `
    <my-cmp [font-size]="100"></my-cmp>
  `
})

See this plnkr (Updated to beta.1)

like image 85
Eric Martinez Avatar answered Oct 19 '22 16:10

Eric Martinez


For specific style, you can also use this:

<div class="theme-preview" [style.font-size]="fontSize+'px'">
like image 17
nir Avatar answered Oct 19 '22 15:10

nir