I have such sort of code in jQuery:
$('#btn').click(function(){
if($('.element').hasClass('active')){
$('.element').removeClass('active');
}
else{
$('.element').addClass('active');
}
});
What would be the analogue of such code in Angular2. I suppose I have to put that in to related component. Any thoughts?
According to the expression
's value, which is true or false active
class is removed and added. To learn more go to documentation
<div [ngClass]="{active:expression}"></div
Read and set the class with @Input()
and `@HostBinding()
@Component({
selector: 'sub-ele',
template: `
<div>hasActiveClass: {{hasActive}}</div>
<button (click)="toggle()">toggle</button>
`
})
export class MyComponent {
// read all classes from the DOM
@Input('class') classes;
// reflect the hasActive state to the DOM
@HostBinding('class.active') hasActive = false;
toggle() {
this.hasActive = !this.hasActive;
}
// initialize the `hasActive` state
ngOnInit() {
this.hasActive = this.classes &&
this.classes.split(' ').indexOf('active') != -1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.