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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36908737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:26:44  来源:igfitidea点击:

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

csstypescriptangular

提问by Vassilis Pits

I want to give a class to the host element of my component so until now I used the hostproperty like this:

我想为我的组件的宿主元素提供一个类,所以直到现在我使用了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() {
  }

}

Now though I'm getting a warning from TypeScript that this is a bad practice.

现在虽然我从 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.

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; }

回答by Günter Z?chbauer

The Angular2 style guide says to prefer @HostBinding, but this doesn't make host: {...}a bad thing.

Angular2 风格指南说是首选@HostBinding,但这并不是host: {...}坏事。

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

}