I want to give a class to the host element of my component so until now I used the host
property like this:
@Component({
selector: 'left-bar',
host: { 'class': 'left-bar' },
templateUrl: 'app/left-bar/left-bar.component.html',
styleUrls: ['app/left-bar/left-bar.component.css']
})
export class LeftBarComponent implements OnInit {
ngOnInit() {
}
}
Now though I'm getting a warning from TypeScript that this is a bad practice.
[tslint] In the "@Component" class decorator of the class "LeftBarComponent" you are using the "host" property, this is considered bad practice. Use "@HostBindings", "@HostListeners" property decorator instead.
How can I add a class to the host element in a more correct way and get rid of this warning?
Thx!
Update: Based on the answer below: I get the class but the style is not affecting the parent host element after the class is added. My style is quite simple:
.left-bar {
position: fixed;
width: 120px;
left: 0;
top: 0;
bottom: 0;
background: #323232; }
The Angular2 style guide says to prefer @HostBinding
, but this doesn't make host: {...}
a bad thing.
You can use
@Component({
selector: 'left-bar',
templateUrl: 'app/left-bar/left-bar.component.html',
styleUrls: ['app/left-bar/left-bar.component.css']
})
export class LeftBarComponent implements OnInit {
@HostBinding('class.left-bar') leftBarClass = true;
// or @HostBinding('class') leftBarClass = 'left-bar';
ngOnInit() {
}
}
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