首页 > 解决方案 > 选定组件的角度显示标题

问题描述

我的问题很简单。

我的结构

例如,在router-outletI display my pages 中/contact/home/meetus

(如何)我可以在 ? 中显示活动组件的名称{{title}}

这甚至可能吗,还是我必须在每个组件中移动我的标题栏?

标签: angulartypescriptcomponentstitle

解决方案


您可以创建一个AppService来保存应用程序title并将其作为可观察对象提供(使用访问器方法,例如getand set)。

@Injectable()
export class AppService {
  private title = new BehaviorSubject<String>('App title');
  private title$ = this.title.asObservable();

  constructor() {}

  setTitle(title: String) {
    this.title.next(title);
  }

  getTitle(): Observable<String> {
    return this.title$;
  }
}

然后在一个将保存(并显示) 的组件(比如说AppComponent)中title,您订阅该appService#getTitle()方法并title相应地更新属性。

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title: String;

  constructor(private appService: AppService) { }

  ngOnInit() {
    this.appService.getTitle().subscribe(appTitle => this.title = appTitle);
  }
}

现在在每个组件中注入AppService(当需要更新标题时)并调用appService#setTitle(). 例如,一个hello组件:

@Component({
  selector: 'hello',
  template: `<p><b>Hello</b> component content</p>`,
  styles: []
})
export class HelloComponent  {
  
  constructor(private appService: AppService) { }

  ngOnInit() {
    this.appService.setTitle('Hello Component');
  }
}

请参阅此工作演示(使用 Angular 6 测试)


推荐阅读