文章目录
一、父子组件数据监听(OnChange)
父组件
使用eChartConfig传入子组件参数
<app-echart [eChartConfig]="config"></app-echart>
子组件
export class EchartComponent implements OnChanges {
@Input() private eChartConfig: any;
ngOnChanges(changes: SimpleChanges): void {
console.log(changes.eChartConfig)
//进行自己数据的调用
this.createChart()
}
}
二、OnChange方式数据改变但是页面没有变化,使用如下三种方式
1.使用ChangeDetectorRef,手动触发变更检测
ChangeDetectorRef 是 Angular 中的一个服务,用于手动触发变更检测。
父组件
.html
<app-echart [eChartConfig]="data"></app-echart>
.ts
//引入ChangeDetectorRef
import {
ChangeDetectorRef,
} from "@angular/core";
export class GridViewComponent {
//进行变量定义
constructor(private cdr: ChangeDetectorRef) { }
data:any
//在数据修改的地方
click(){
this.data = 1
this.cdr.detectChanges()
}
}
2.使用Subject,观察者和订阅者模式进行数据监听
父组件
import {Subject} from "rxjs";
export class GridViewComponent {
//进行变量定义
eChartConfig$ = new Subject<any>()
//在数据修改的地方
click(){
this.data = 1
//进行发布
this.echartProgressConfig$.next(this.data)
this.cdr.detectChanges()
}
子组件
import {Subject} from "rxjs";
export class GridViewComponent implements AfterViewInit{
eChartConfig$= new Subject<any>()
ngAfterViewInit() {
console.log(this.eChartConfig$)
// 订阅数据
this.eChartConfig$.subscribe(eChartConfig=>{
// 打印改变的数据
console.log(eChartConfig)
// 调用改变的数据
this.createChart(eChartConfig);
})
}}
3.自定义数据监听事件
使用自定义的refresh()方式进行数据的监听和修改,也是一定可以成功的方式
父组件
.html
<button (click)="click()"><button>
<ng-container>
<ng-container *ngTemplateOutlet="echart;context:{$implicit:eChartConfig}">
</ng-container>
</ng-container>
<ng-template #echart let-config>
<app-echart [eChartConfig]="config"></app-echart>
</ng-template>
.ts
export class GridViewComponent implements OnInit {
constructor(private cdr: ChangeDetectorRef) {}
eChartConfig: any = {
eChartsType: '',
xData: [],
yData: []
}
click(){
this.eChartConfig = {
eChartsType:'1',
xData='2',
yData='3'
}
//数据改变进行刷新
this.cdr.detectChanges()
}
}
子组件
export class EchartComponent implements AfterViewInit, OnInit,OnChanges {
@Input() private eChartConfig: any;
//数据改变,进行监听配置
ngOnChanges(changes: SimpleChanges): void {
this.refresh()
}
/**
* 根据配置刷新视图
*/
refresh(){
this.chart?.dispose()
this.createChart(this.eChartConfig);
}
/**
* 设置配置
* @param config
*/
setConfig(config:any){
this.eChartConfig = config;
this.refresh()
}
ngAfterViewInit() {
this.refresh()
}
}