2016-05-16 69 views
5

我有一個組件,它是所有渲染,它是這樣的:主機元素有條件的造型

@Component({ 
    selector: 'my-comp', 
    host: ???, 
    template: ` 
     <ng-content></ng-content> 
    ` 
}) 

export default class MyComp { 
    @Input() title: string; 
    public isChanged: boolean; 
} 

該組件有一個isChanged性能,我想基於主機元素上應用樣式isChanged屬性。這甚至有可能嗎?

回答

4

您使用classstyle前綴這一點。下面是一個示例:

@Component({ 
    selector: 'my-comp', 
    host: { 
    '[class.className]': 'isChanged' 
    }, 
    template: ` 
    <ng-content></ng-content> 
    ` 
}) 
export default class MyComp { 
    @Input() title: string; 
    public isChanged: boolean; 
} 

見岡特的更多細節的答案:

+1

也許簡單'[class.className]':'isChanged' – yurzui

+0

@yurzui:是的,你完全正確!它的屬性,你需要有一個空值來刪除它;-)我更新了我的答案。謝謝! –

0

不知道你想要做什麼,但這樣的事情就足夠了,你用ngAfterViewInitElementRef

import {AfterViewInit, ElementRef} from '@angular/core'; 

@Component({ 
    selector: 'my-comp', 
    host: ???, 
    template: ` 
    <ng-content></ng-content> 
    ` 
}) 

export default class MyComp implements AfterViewInit { 
    @Input() title: string; 
    public isChanged: boolean; 

    constructor(private _ref: ElementRef) {} 

    ngAfterViewInit() { 

    var host = this._ref.nativeElement; 

    if (this.isChanged) { 
     host.style.width = '200px'; 
    } 
    } 
} 

如果你希望每次它改變了你可以實現ngDoCheck時間做一些檢查爲isChanged而不是/還有:

ngDoCheck() { 

    if (this.isChanged !== this.previousIsChanged) { 

    var host = this._ref.nativeElement; 

    if (this.isChanged) { 
     host.style.width = '200px'; 
    } 
    } 
} 
0

我想你想要讓你的組件火災可以由被逮住的事件主機(並可能傳遞一些數據)。

要做到這一點,你將有一個@output屬性,如:

@Output() isChanged: EventEmitter<any> = new EventEmitter() 

然後在你的代碼,你可以這樣做:

this.isChanged.emit(some value to pass) 

它接住喜歡:

(isChanged)="doSomething($event)"