I'm not sure how to use ngStyle
directive with latest beta-12. Could someone please clarify.
The plnkr link in Angular docs https://angular.io/docs/js/latest/api/common/NgStyle-directive.html is outdated, it uses alpha build.
I tried these syntax but does not seem to work. I
[ngStyle]="{'display': none}"
[style.display]="none"
http://plnkr.co/edit/U9EJuIhFqxY9t2sULMdw
import {Component} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2 [ngStyle]="{'display': none}">Hello {{name}}</h2>
<h2 [style.display]="none">Hello {{name}}</h2>
</div>
`,
directives: []
})
export class App {
constructor() {
this.name = 'Angular2'
}
}
In both cases, none
should be 'none'
with quotes. Because you should be assigning string
value to the property display
. none
(without qoutes) will be evaluated at runtime and return undefined
which is not an acceptable value of the css property display
//our root app component
import {Component} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2 [ngStyle]="{'display': 'none'}">Hello {{name}}</h2>
<h2 [style.display]="'none'">Hello {{name}}</h2>
</div>
`,
directives: []
})
export class App {
constructor() {
this.name = 'Angular2'
}
}
Here is your plunker fixed
Update
This is from angular2 docs for NgClass directive:
The result of an expression evaluation is interpreted differently depending on type of the expression evaluation result:
string - all the CSS classes listed in a string (space delimited) are added
Array - all the CSS classes (Array elements) are added
Object - each key corresponds to a CSS class name while values are interpreted as expressions evaluating to Boolean. If a given expression evaluates to true a corresponding CSS class is added - otherwise it is removed.
@Component({
selector: 'my-app',
providers: [],
styles:['.hide{display:none}',
'.border{border:3px solid blue}',
'.redBack{background-color:red}'
],
template: `
<div>
<h2 [ngStyle]="{'display': 'none'}">Hello {{name}}</h2>
<h2 [style.display]="'none'">Hello {{name}}</h2>
<h2 [ngClass]="'redBack'">Hello {{name}}</h2> // just normal string
<h2 [ngClass]="{'hide':hideFlag}">Hello {{name}}</h2> // will add class 'hide' if hideFlag is true
<h2 [ngClass]="mulClasses">Hello {{name}}</h2> // will add an array of classes ['border','redBack']
</div>
`,
directives: []
})
export class App {
hideFlag = false;
mulClasses = ['border','redBack']
constructor() {
this.name = 'Angular2'
}
}
here is the example in plunker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With