2016-12-06 47 views
2

任務是根據路徑更改背景顏色。我必須爲UpcomingComponent顯示不同的顏色,而對於其他路線,背景顏色將保持不變。以組件Angular 2的樣式設置值

我試圖在STYLES中爲for/deep/.classname動態設置背景顏色的值。

下面是代碼

@Component({ 
    selector: 'app-upcoming', 
    templateUrl: './upcoming.component.html', 
    // styleUrls: ['./upcoming.component.css'], 

    styles: [` 
    /deep/ .root { 
    background-color: color; 
    }`] 
}) 

export class UpcomingComponent implements OnInit { 

    color: string; 


    ngOnInit() { 
    this.bodyBackgroundImage(); 
    } 



    bodyBackgroundImage() { 
    if (window.location.pathname === '/upcoming'){ 
     console.log("Here i am"); 
     this.color = 'purple'; 
    } 

    } 

} 
+1

我認爲這尚未支持。 – micronyks

+0

原因是所有樣式都是在你的類被實例化之前編譯的。 – Milad

回答

0

我已經在AppComponent中使用了Route。感謝@GünterZöchbauer幫助我。

import { Component } from '@angular/core'; 
import {Router , ActivatedRoute,NavigationEnd} from '@angular/router'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 

}) 
export class AppComponent { 


    constructorprivate router:Router,private activatedRoute:ActivatedRoute) { 

    router.events.subscribe(event => { 
     if (event instanceof NavigationEnd) { 
     if (event.url === '/upcoming') { 
      document.body.style.background = 'grey'; 
     }else { 
      document.body.style.background = 'blue'; 
     } 
     } 
    }); 
    } 
} 
1

stylesstyleUrls綁定不支持。請使用[class.xxx]="...",[ngClass]="...",[style.xxx]="...",[ngStyle]="..."種類的要綁定的元素樣式。

+0

我想改變body元素的背景顏色。 –

+0

如果''body''作爲選擇符,或者只是'document.body.style.background =',則可以在'AppComponent'中使用'@HostBinding('style.background-color')bgColor ='red';'紅色';'從任何地方。 –

+0

謝謝你的回答。但它正在改變所有的路線。我希望它改變爲特定的路線。我試圖做到這一點bodyBackgroundImage()如果(window.location.pathname ==='/即將推出'){ console.log(「Here i am」); document.body.style.background ='blue'; } –

相關問題