Angular 选定零部件的角度显示标题
我的问题很简单 在Angular 选定零部件的角度显示标题,angular,typescript,components,title,Angular,Typescript,Components,Title,我的问题很简单 在路由器出口中,我显示我的页面,例如/contact、/home或/meetus (如何)在{{title}中显示活动组件的名称 这是可能的还是我必须在每个组件内移动标题栏?您可以: 创建一个新组件,将其称为标题,并将其放置在页面中。此组件将负责显示标题/您喜欢的任何标题 当有人输入特定组件时,使用服务并更新标题变量 你可以这样做 在模板上 <router-outlet (activate)="onActivated($event)"></router-out
路由器出口
中,我显示我的页面,例如/contact
、/home
或/meetus
(如何)在{{title}
中显示活动组件的名称
这是可能的还是我必须在每个组件内移动标题栏?您可以:
标题
,并将其放置在页面中。此组件将负责显示标题/您喜欢的任何标题标题
变量<router-outlet (activate)="onActivated($event)"></router-outlet>
您可以使用角度按钮在页眉组件中显示页面标题,如下所示:
标题组件。ts:
export class AppComponent {
public constructor(private titleService: Title ) { }
}
Header component.html:
<div class="title-bar">
{{titleService.getTitle()}}
</div>
您可以创建一个包含应用程序标题
,并将其作为可观察对象提供(使用访问器方法,如get
和set
)
现在,在每种情况下,您都会插入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');
}
}
@组件({
选择器:“你好”,
模板:`Hello组件内容`,
样式:[]
})
导出类HelloComponent{
构造函数(私有appService:appService){}
恩戈尼尼特(){
this.appService.setTitle('Hello Component');
}
}
查看此(使用Angular 6进行测试)除了选择器之外,我还可以使用任何东西吗?那么,添加一个名称或什么?是的,它只是一个变量名称。我如何确切地使用变量?当我在组件中创建变量title时,this.resolver.resolveComponentFactory(component.constructor).title不起作用。抱歉,我是Angular的新手。你不能这样做,只是为了得到你在组件中使用的选择器的名称,如果你想共享一个变量,你应该实现另一个答案中提到的服务。谢谢,这就像champ!是否可以将我的浏览器标题与此标题区分开来?您可以根据浏览器标题在标题中显示某个标题。例如,将浏览器标题设置为“联系人”,并使用标题服务检入标题组件如果浏览器标题为“联系人”,则显示“联系我们”例如,在标题标题中。您还可以创建一个浏览器标题数组作为键,标题标题数组作为值,并显示当前浏览器标题的相应标题,而无需使用if。@AliRida an,以便仅在标题更改时收到通知。这是真的@Lealcelderio,有许多解决方案,这取决于需求和项目结构。谢谢你的完美回答。还有一件事丢失了,那就是在app.module.ts
providers:[AppService]
@imdadhusen中注册了提供商。感谢您的反馈:)很高兴它对您有所帮助。您提到的那段代码在“you are correct”代码中已经存在,但您只是在解释中没有提到。对于angular 11,未工作错误:NG0100:ExpressionChangedTerithasBeenCheckedError:表达式在检查后已更改。
export class AppComponent implements OnInit { {
public constructor(private titleService: Title ) { }
ngOnInit() {
this.titleService.setTitle("Component's title");
}
}
@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$;
}
}
@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({
selector: 'hello',
template: `<p><b>Hello</b> component content</p>`,
styles: []
})
export class HelloComponent {
constructor(private appService: AppService) { }
ngOnInit() {
this.appService.setTitle('Hello Component');
}
}