2016-12-06 39 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'; } –

相关问题