【问题标题】:How to give class to a host element in Angular 2 with @hostbinding如何使用 @hostbinding 为 Angular 2 中的宿主元素提供类
【发布时间】:2016-08-22 20:49:27
【问题描述】:

我想给我的组件的宿主元素一个类,所以直到现在我都使用了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.

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

谢谢!

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

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

【问题讨论】:

    标签: css typescript angular


    【解决方案1】:

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

    【讨论】:

    • Thx,添加了类,但是当我这样做时,我的样式不会影响宿主元素。
    • 如果确实添加了该类,您是否检查了浏览器开发工具?可能你的风格不对。
    • 是的,添加了类,我验证了样式是正确的。它适用于所有子元素,但不适用于宿主元素。
    • 太棒了!使用@HostBinding() 添加一个类是当您在父组件上具有应该应用于您的组件的样式时(例如,取决于它的内部状态反映到添加或删除的类)
    • @GünterZöchbauer @HostBinding('class') siteNavbarSmallClass = 'login-form login-form-second page-login-second';它也适用于我!谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2016-10-19
    • 2019-07-15
    相关资源
    最近更新 更多