2016-01-06 16 views
69

我不知道如何添加到我的組件<component></component>動態屬性但在模板html(component.html)中。如何將「class」添加到主機元素?

我發現的唯一解決方案是通過「ElementRef」本地元素修改該項目。這個解決方案似乎有點複雜,要做一些應該很簡單的事情。

另一個問題是CSS必須在組件範圍之外定義,打破組件封裝。

有沒有更簡單的解決方案?像模板內的<root [class]="..."> .... </ root>

+1

可能重複[如何通過打字稿類(angular2)更改主體類](http://stackoverflow.com/questions/34636661/how-do-i-change-the-body-class -via-a-typecript-class-angular2) –

+0

是的,這個解決方案也可以,但也太可怕了:)。另一個問題是,CSS必須在組件範圍之外定義! (與ElementRef一樣)。 – lascarayf

回答

140
@Component({ 
    selector: 'body', 
    template: 'app-element', 
    // prefer decorators (see below) 
    // host:  {'[class.someClass]':'someField'} 
}) 
export class App implements OnInit { 
    constructor(private cdRef:ChangeDetectorRef) {} 

    someField: boolean = false; 
    // alternatively also the host parameter in the @Component()` decorator can be used 
    @HostBinding('class.someClass') someField: boolean = false; 

    ngOnInit() { 
    this.someField = true; // set class `someClass` on `<body>` 
    //this.cdRef.detectChanges(); 
    } 
} 

Plunker example

這樣你就不需要添加組件之外的CSS。 CSS像從組件的內部與選擇器

:host(.someClass) { 
    background-color: red; 
} 

作品如果類someClass被設置在主機元件上僅適用。

+0

我不得不在'ngOnInit()' - 方法中執行'someField = true',而不是'ngAfterViewInit()'。否則我無法讓它工作。 – John

+0

[Made a fork here](https://plnkr.co/edit/UsHyi78eza01N25ulxzA?p=preview)顯示實際的':host'部分工作。我在哪裏可以瞭解更多關於@Component()裝飾器中的主機參數(語法對我來說不是很明顯,[@Component文檔沒有解釋太多](https://angular.io/docs/ts/latest /api/core/index/Component-decorator.html))或瞭解更多關於您首選的HostBinding(它只是[列爲接口](https://angular.io/docs/ts/latest/api/core/index /HostBinding-interface.html)? –

+0

我不知道更好的文檔,但它只是一種不同的方式來處理你可以用@Input()來執行的操作@ @Output()@@HostBinding() )''@HostListener()''@ViewChild(ren)()''@ContentChild(ren)()' –

79

君特的回答是偉大的(問題是要求動態類屬性),但我想我會添加只是爲了完整性...

如果你正在尋找一個快速和清潔的方式來增加一個或更靜態類的組件的主元素(即,爲主題造型的目的),你可以這樣做:

@Component({ 
    selector: 'my-component', 
    template: 'app-element', 
    host: {'class': 'someClass1'} 
}) 
export class App implements OnInit { 
... 
} 

如果你在輸入標籤使用一個類,角將合併類,即,

<my-component class="someClass2"> 
    I have both someClass1 & someClass2 applied to me 
</my-component> 
+1

爲了簡單起見,喜歡這個。然而,在我的情況下,host元素被封裝了一個不同的屬性,我們把它稱爲'ngcontent_host',而不是我的模板中元素的任何屬性'',所以我們調用那些'ngcontent_template',所以如果我把'styleUrls'我的組件,它們不會影響主機元素,因爲它們不會影響'ngcontent_host',它們只能影響模板元素;它們只能影響'ngcontent_template'。我錯了嗎?對此有何建議?我想我總是可以變成'ViewEncapsulation.None' –

+0

糟糕,也許是因爲Günter說:特殊的':主機'選擇器。 [更多信息](https://angular.io/docs/ts/latest/guide/component-styles.html#-host) –

+0

非常簡單和有效的解決方案,將類添加到組件的主機元素。我在我的應用程序中使用這個。謝謝分享! – Devner