angular - 选定组件的角度显示标题
问题描述
我的问题很简单。
例如,在router-outlet
I display my pages 中/contact
,/home
或/meetus
(如何)我可以在 ? 中显示活动组件的名称{{title}}
?
这甚至可能吗,还是我必须在每个组件中移动我的标题栏?
解决方案
您可以创建一个AppService来保存应用程序title
并将其作为可观察对象提供(使用访问器方法,例如get
and 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 测试)
推荐阅读
- postman - 邮递员收集异步运行
- tensorflow - 如何在 tensorfow keras 中添加 2 个模型路径?
- rest - 在浏览器和 NodeJS 或 curl 中使用 Stack Exchange API 时的不同数据格式
- html - HTML 视频在 iPhone 上不可见
- vue.js - 折线图不呈现数据
- asp.net-core - Strict-Transport-Security 标头没有价值
- grpc - 如何为 grpc-java 客户端指定 User-Agent 标头?
- algorithm - 如何找到从 2 到 N + 1 的组总数
- r - 如何在大数据集中找到 30 个最常见的值?
- c# - 在列名是动态 c# LINQ 的动态列表上实现多个“Where”条件