我有一个组件,它只在app.component.html中使用。此页脚存在于所有页面上。我想在组件上改变它的背景颜色。页脚的样式在footer.component.css中。那么我该怎么做呢?
发布于 2019-08-30 00:32:20
在footer.component.css上,您使用的是原始颜色。
如果您在app.component上使用页脚(组件名称: my- footer ),如下所示:
<my-footer></my-footer>你可以在app.component.css上添加一些css来覆盖原始颜色。
my-footer ... {
background-color: red
}发布于 2019-08-30 04:11:01
你需要告诉Angular页面发生了变化,并在这种变化发生时做出一些改变。一种方法是订阅router.event。所以,假设你有一个这样的app.component
<div class="container">
<a routerLinkActive="active"
routerLink="/one">One</a> |
<a routerLinkActive="active"
routerLink="/two">Two</a> |
<a routerLinkActive="active"
routerLink="/three">three</a>
<router-outlet></router-outlet>
<footer [style.background-color]="color"></footer>
</div>在组件的ngOnInit中,您可以订阅,因此
ngOnInit()
{
this.router.events.pipe(filter(event=>event instanceof NavigationEnd)).subscribe((res:any)=>{
switch (res.url)
{
case "/one":
this.color="orange"
break;
case "/two":
this.color="pink"
break;
case "/three":
this.color="silver"
break;
}
})
}您可以在stackblitz中看到一个示例
注意:在这种情况下,使用style.ground-color,您还可以使用ngClass,并更改订阅以提供不同的类
更新了如果您不想使用路径,始终可以创建服务
export class BkService {
private colorSubject=new Subject<any>()
colorObservable=this.colorSubject.asObservable();
constructor() { }
setColor(color:any)
{
this.colorSubject.next(color);
}
}然后您可以在app.component的ngOnInit中进行订阅
this.bkService.colorObservable.subscribe(res=>{
this.borderColor=res;
})每个组件,在ngOnInit中你都可以做,例如
constructor(private bkService:BkService){}
ngOnInit()
{
this.bkService.setColor('red');
}使用服务编辑了2个,您也可以使用简单的变量
在app.component中
get fontSize()
{
return this.bkService.fontSize;
}并且在每个组件中
this.bkService.fontSize=".5rem"https://stackoverflow.com/questions/57714203
复制相似问题