Angular2 在组件之间共享数据

标签 angular components

您好,我想在组件之间共享标题。我有组件 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";
  }
}

为了更清晰,我添加了图像: Communication between components

我想在任何组件(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/

相关文章:

javascript - React 不将 props 传递给 child

oop - 当没有传入所有参数时,如何调用父方法?

javascript - React 组件分解策略

date - 如何在angular2中格式化日期?

javascript - 使用 NGStyle 通知用户已进行更改

Angular 6 : Multiple configurations (twas environments)

css - 从位于 JSON 中的 url 获取图像

angular - Angular 2 Material 中的粘性页脚

java - 使用几何形状作为组件

javascript - 如何在 react 中导入根路径之外的组件?