您好,我想在组件之间共享标题。我有组件 app.component 声明 title 属性,所有其他组件都是子组件。我有将标题写入 html 的 page-header.component 和设置 title 属性且标题不显示的dashboard.component。这是我的代码:
应用程序组件
export class AppComponent implements OnInit {
title: string;
ngOnInit(): void {
}
}
页面标题.组件
export class PageHeaderComponent extends AppComponent implements OnInit {
constructor() {
super();
}
ngOnInit() {
super.ngOnInit();
}
}
page-header.component.html
<h1>{{title}}</h1>
仪表板组件
export class DashboardComponent extends AppComponent {
constructor() {
super();
}
ngOnInit() {
super.ngOnInit();
this.title = "Dashboard";
}
}
我想在任何组件(AppComponent 的子组件)中轻松设置标题,并且标题将写入页眉组件
最佳答案
你把事情变得过于复杂了,你有两种方法可以以 Angular 方式共享数据,无论是使用服务还是使用 @Input
装饰器,就像这样
在page-header.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<h1>{{title}}</h1>
`
})
export class PageHeaderComponent {
@Input() title: string;
}
在 page-header.component.ts
的父组件(即 app.component.ts
)中,您执行以下操作
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child [title]="parentTitle"</app-child>
`
})
export class AppComponent {
@Input() parentTitle: string;
}
在 app.component.ts
的父组件中,这是您所做的 dashboard.component.ts
import {Component} from '@angular/core';
@Component({
selector: 'app-parent-parent'
template : `
<app-parent [parentTitle] = "parentParentTitle"</app-parent>
`
})
export class DashboardComponent {
parentParentTitle = "Dashboard";
}
或者,您可以创建一个带有 setter 和 getter 方法的服务,并将其注入(inject)到三个组件中以在所有组件之间设置或获取数据。
关于Angular2 在组件之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44175781/