【问题标题】:Change app component style from any child component - Angular 2从任何子组件更改应用程序组件样式 - Angular 2
【发布时间】:2017-02-02 23:53:22
【问题描述】:
我想从子组件改变应用组件(父组件)的背景。
假设我有两组组件,一组是主要组件,可以从应用程序直接访问
组件菜单和其他组是次要组件,将从主要组件菜单/链接访问。
所以在这里我想根据加载的主要和次要组件来更改应用程序组件背景
https://plnkr.co/edit/t97ZyDz9wfGuPEzuo8J3?p=preview
app.component.css
.page-background
{
background-color:#FFF0F5;
}
.page-background-hero
{
background-color:white;
}
.page-background-crisis
{
background-color:wheat;
}
【问题讨论】:
标签:
angular
angular2-routing
angular2-template
【解决方案1】:
您应该在子组件中使用样式属性,并使用指定背景颜色的 div 元素包装内容。
危机中心儿童组件
@Component({
template: `
<div class="red">
<h2>CRISIS CENTER</h2>
<router-outlet></router-outlet>
</div>
`,
directives: [RouterOutlet],
providers: [CrisisService],
styles:[`.blue{background-color:red} `]
})
英雄列表子组件
@Component({
template: `
<div class="yellow">
<h2>HEROES</h2>
<ul>
<li *ngFor="#hero of heroes"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
</div>
`
styles:[`.yellow{background-color:yellow} `]
})
UPDATED PLUNK
【解决方案2】:
您可能需要考虑使用shared service 进行这种父子通信。
父母可以订阅服务,孩子在加载时推送背景样式等信息(通过ngOnInit)
另一种选择是让父组件通过ContentChildren 访问子组件以确定将背景更改为哪种颜色。