Rob*_*ter 4 components title typescript angular
我的问题很简单。
router-outlet例如/contact,在我显示我的页面中,/home或/meetus
(如何)我可以在{{title}}?
这甚至可能还是我必须在每个组件内移动我的标题栏?
可以创建一个一个AppService服务,其保持应用title,并提供它作为一个可观察到的(与存取方法如get和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$;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在一个将持有(并显示) 的组件(假设为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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在在每个组件中注入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');
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅此工作演示(使用 Angular 6 测试)
| 归档时间: |
|
| 查看次数: |
7333 次 |
| 最近记录: |