如何使用@hostbinding将类赋予Angular 2中的宿主元素 [英] How to give class to a host element in Angular 2 with @hostbinding

查看:50
本文介绍了如何使用@hostbinding将类赋予Angular 2中的宿主元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给组件的host元素一个类,所以直到现在我还是这样使用 host 属性:

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

}

现在,尽管我收到来自TypeScript的警告,这是一种不好的做法.

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?

谢谢!

更新:基于以下答案:我得到了该类,但是添加该类后,样式不会影响父级宿主元素.我的风格很简单:

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

推荐答案

Angular2样式指南说偏爱 @HostBinding ,但这不能成为 host:{...}是一件坏事.

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

您可以使用

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

}

这篇关于如何使用@hostbinding将类赋予Angular 2中的宿主元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆