Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give class to a host element in Angular 2 with @hostbinding

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; }
like image 720
Vassilis Pits Avatar asked Apr 28 '16 08:04

Vassilis Pits


1 Answers

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() {
  }

}
like image 77
Günter Zöchbauer Avatar answered Nov 04 '22 07:11

Günter Zöchbauer