您好,我想在组件之间共享标题。我有组件app.component,它声明title属性,所有其他组件都是子组件。我有page-header.component将标题写入html,而dashboard.component将标题属性和标题设置为不显示。这是我的代码:
应用组件
export class AppComponent implements OnInit {
title: string;
ngOnInit(): void {
}
}
page-header.component
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的子组件)中轻松设置标题,并且标题将写入页面标题组件中
最佳答案
您使事情变得过于复杂,无论是通过使用服务还是通过使用@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方法创建服务,然后将其注入三个组件中以设置或获取所有组件之间的数据。
关于angular - Angular2在组件之间共享数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44175781/