【发布时间】:2018-12-19 13:07:09
【问题描述】:
我的问题很简单。
在router-outlet 中显示我的页面,例如/contact、/home 或/meetus
(如何)在{{title}} 中显示活动组件的名称?
这甚至可能吗,还是我必须在每个组件中移动我的标题栏?
【问题讨论】:
标签: angular typescript components title
我的问题很简单。
在router-outlet 中显示我的页面,例如/contact、/home 或/meetus
(如何)在{{title}} 中显示活动组件的名称?
这甚至可能吗,还是我必须在每个组件中移动我的标题栏?
【问题讨论】:
标签: angular typescript components 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$;
}
}
然后在一个将保存(并显示)title 的组件(比如说AppComponent)中,订阅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);
}
}
现在在每个component 中注入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');
}
}
查看此Working Demo(使用 Angular 6 测试)
【讨论】:
providers: [AppService] 中注册提供程序
您可以使用 Angular titleService 在标题组件中显示页面标题,如下所示:
头组件.ts:
export class AppComponent {
public constructor(private titleService: Title ) { }
}
头组件.html:
<div class="title-bar">
{{titleService.getTitle()}}
</div>
然后在任何组件中,您都可以使用 Angular titleService 设置页面标题,它会在标题和标题部分中自动更改:
export class AppComponent implements OnInit { {
public constructor(private titleService: Title ) { }
ngOnInit() {
this.titleService.setTitle("Component's title");
}
}
【讨论】:
你可以:
创建一个新组件,将其命名为header,并将其放置在您的页面中。该组件将负责显示标题/您喜欢的任何标题
当有人进入特定组件时,使用服务并更新title 变量
【讨论】:
constructor(private resolver: ComponentFactoryResolver) {}
onActivated(component) {
this.activeSelector =
this.resolver.resolveComponentFactory(component.constructor).selector;
}
在模板上,
<router-outlet (activate)="onActivated($event)"></router-outlet>
【讨论】: