Angular2在组件之间共享数据 [英] Angular2 Share data between components

查看:159
本文介绍了Angular2在组件之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想在组件之间共享标题。我有组件app.component,它声明title属性,所有其他组件都是子组件。我有page-header.component将标题写入html,而dashboard.component将标题属性和标题设置为不显示。这是我的代码:

Hello i would like to share title between components. I have component app.component which declare title property and all another components are children. I have page-header.component which write title to html and dashboard.component which set title property and title dont show. Here is my code:

app.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();
  }

}

页面标题。 component.html

<h1>{{title}}</h1>

dashboard.component

export class DashboardComponent extends AppComponent {

  constructor() {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    this.title = "Dashboard";
  }
}

为了更清晰起见,我添加了图像:

For greater clarity i added image:

我想在任何组件(AppComponent的子组件)中轻松设置标题,并将标题写入页面标题组件

I would like to easy set title in any component (child of AppComponent) and title will be write to page header component

推荐答案

您正在使事情变得过于复杂,无论是通过使用服务还是使用<$ c,都有两种方式共享角度数据$ c> @Input 装饰器就像这样

you are overcomplicating things you have two ways to share data in angular whether by using a service or by using the @Input decorator just like this

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 ,您可以执行以下操作

in the parent component of page-header.component.ts which is app.component.ts you do the following

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

and in the parent component of app.component.ts which is the dashboard.component.ts you do

import {Component} from '@angular/core';

@Component({
selector: 'app-parent-parent'
template : `
<app-parent [parentTitle] = "parentParentTitle"</app-parent>
`
})
  export class DashboardComponent {
 parentParentTitle = "Dashboard";     
 }

或者,您可以使用setter和getter方法创建服务,然后注入在三个组件之间进行设置或获取数据。

alternatively, you can create a service with a setter and getter methods and you inject it in the three components to set or get data between all of them.

这篇关于Angular2在组件之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆