如何从Angular 2中的嵌套组件更改父背景图像?

时间:2016-08-13 17:06:17

标签: javascript css angular encapsulation

对于我的应用程序中的每个路径,我需要更改父背景图像。我在每个嵌套组件中使用style属性来实现这一点,在每个组件中将ViewEncapsulation设置为None,这样它就会产生全局效果。这是有效的,但问题是当我浏览应用程序时,我在head标签中得到了这个样式的多个实例:

<style>...</style>
<style>...</style>

以下是子组件的代码:

import {Component, Output, EventEmitter} from '@angular/core';
import {ViewEncapsulation} from '@angular/core';

@Component({
    selector: '',
    templateUrl:'app/home.component.html',
    styles: [`
              .hero-unit {
                  background:url('/app/assets/images/hero-01.png');
                  width:100%;
                  height:540px;
                  background-size: cover;
                  background-repeat: no-repeat;
                  background-position: 50% 50%;
              }
            `],

    encapsulation: ViewEncapsulation.None
})
export class HomeComponent {

}

一个覆盖另一个可以正常,直到您尝试导航回上一页,效果停止工作。我的问题是,有一种方法可以在我离开该组件后删除一个样式属性,并在我向后导航时将其重新插入。或者,是否有更好的方法根据路线换出背景图像。我很难找到在Angular 2中实现这么简单任务的最佳方法。谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用路由器数据或服务。

路由器解决方案

将图片网址放在路线数据中:

{ path:      'child1', 
  component: Child1Component,
  data:      { imageUrl: '/app/assets/images/hero-02.png' }
}

然后,父组件可以订阅路由事件,提取URL并更新样式属性:

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

@Component({
  template: `<section>
    UserComponent content here, if any.
    <nav>
       <a [routerLink]="['./']">Activity</a>
       <a [routerLink]="['profile']">Profile</a>
       - child routes
    </nav>
    <div class="child-view">
      <router-outlet></router-outlet>
    </div>
    <section>`
})
export class UserComponent {
  constructor(private router: Router, private route: ActivatedRoute, 
    private renderer:Renderer, private elref:ElementRef) {}
  ngOnInit() {
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(_ => { 
          let childRouteSnapshot = this.route.firstChild.snapshot;
          let url = childRouteSnapshot.data.imageUrl;
          this.renderer.setElementStyle(this.elref.nativeElement.childNodes[0],
            'background-image', 'url(' + url + ')');
      })
  }
}

这是一个有用的 Plunker 。 (注意,plunker中的一些代码只有一半转换为RC5。上面显示的代码都是RC5。)

我必须使用childNodes[0]因为我的示例elref设置为ng-component而不是<section>

服务解决方案

使用共享服务。请参阅食谱部分Parent and children communicate via a service。子组件在父组件订阅的可观察/主题上发布事件(即URL图像字符串)。