Angular 8 组件间数据共享

父子组件数据传递

  • 父级向子级传递对象: @Input

例如:一个下拉框的列表数据 options 来自父组件。

子组件代码:

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

@Input() options: Array<string>;

在子组件中,可以自由使用 options 对象。

在 js 中通过 this.options 去访问列表数据

在 html 中 直接用 options 去访问

父组件中使用

子组件一般直接在父组件的 html 中通过元素的形式添加进来,如

<app-search [options]="StatusStr"> </app-search>

options 是在子组件添加的对外属性,[options] 表示通过数据模型绑定到子组件的 options 属性上。StatusStr 是父组件(js文件)中定义的一个数据对象。

这样就实现了将父组件的数据传递给了子组件。

  • 子组件向父组件触发事件 @Output, EventEmitter

子组件代码:

import { Component, Output, EventEmitter } from '@angular/core';

@Output() search = new EventEmitter<string>();

onSearch(keycode, val) {

if (keycode == 13) {

this.search.emit(val);

}

}

父组件代码:

HTML:

<app-search (search)="searchUsers($event)"></app-search>

JS:

searchUsers(val: string) {

this.searchKey = val;

this.getUsers(val);

}

子组件中使用 @output + EventEmitter 定义一个可以对外的带参事件,并在子组件内部的适当时机去触发这个事件 this.search.emit(val),

父组件在使用子组件时,可以将子组件中定义的事件绑定到自己的内部函数。

子组件通过 @output 定义的event, 使用上等同于html 基本元素的 click 事件,都可以通过 (eventname)的形式进行事件绑定。

同级组件数据传递

没有包含关系的两个组件,如果想进行数据传递,根据业务要求的不同,可以自行选择子父父子参数续传,或者是通过 service。

这里介绍通过 service 实现两个组件间的事件触发及参数传递:

  • 创建一个 service 专门用作各种情况下的 service 数据传递

////selected report

private selectedReportSource = new Subject<any>();

SelectedReport$ = this.selectedReportSource.asObservable();

SelecteReport(index: any) {

this.selectedReportSource.next(index);

}

selectedReportSource 用来保存选中的 report 唯一标志,SelectedReport$ 是一个选中 report 唯一标志的可订阅对象, SelecteReport()方法用来修改选中的 report

  • 在触发改变的组件内,调用数据改变方法

import { AllService } from "../../../services/all.service";

this.all.share.SelecteReport(tabIndex);

import 定义数据服务的对象,通过服务方法改变选中的 report

  • 在接收数据改变的组件内,监听 subject 对象

import { Component, OnInit, OnDestroy } from '@angular/core';

import { AllService } from "../../../services/all.service";

import { Subscription } from 'rxjs';

export class ReportsComponent implements OnInit, OnDestroy {

subscription_selectReport: Subscription;

ngOnInit() {

this.subscription_selectReport = this.all.share.SelectedReport$.subscribe((x: number) => {

this.ActiveTab = x;

});

}

ngOnDestroy() {

this.subscription_selectReport.unsubscribe();

}

}

第一,引入数据服务 AllService

第二,添加组件的 OnDestroy, Subscription 引用

第三,定义一个 Subscription 对象,并注册监听 SelectedReport$.subscribe(),

第四,在 ngOnDestroy 中注销监听(避免内存泄漏)

注意:

如果不需要不同组件间事件的触发,就不需要注册监听,直接在数据服务中提供一个数据访问方法,由数据消费组件调用即可