2016-04-28 8 views
8

を@hostbindingと角度2でホスト要素にクラスを与える方法:しかし今今まで、私はこのような<code>host</code>プロパティを使用して、私は私のコンポーネントのホスト要素にクラスを与えたい

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

答えて

14

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

} 
+0

Thxをし、使用することができます。 –

+0

クラスが実際に追加された場合、ブラウザのdevtoolsをチェックインしましたか?たぶんあなたのスタイルが正しくないかもしれません。 –

+0

はい、クラスが追加され、スタイルが正しいことが確認されました。これは、すべての子要素に対して機能しますが、ホスト要素に対しては機能しません。 –

関連する問題