如何使用@hostbinding为Angular 2中的host元素提供类

时间:2016-04-28 08:04:46

标签: css typescript angular

我想给我的组件的host元素一个类,所以到现在为止我使用了host属性:

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

}

现在虽然我收到了TypeScript的警告,但这是一种不好的做法。

[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.

如何以更正确的方式向主元素添加类并消除此警告?

THX!

更新:基于以下答案:我获得了类,但是在添加类之后样式不会影响父主机元素。 我的风格很简单:

.left-bar {
  position: fixed;
  width: 120px;
  left: 0;
  top: 0;
  bottom: 0;
  background: #323232; }

1 个答案:

答案 0 :(得分:17)

Angular2风格指南表示更喜欢@HostBinding,但这并不会使host: {...}成为一件坏事。

您可以使用

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

}