Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何进行数据双向绑定 #390

Open
sunny2zhang opened this issue Mar 24, 2023 · 1 comment
Open

如何进行数据双向绑定 #390

sunny2zhang opened this issue Mar 24, 2023 · 1 comment

Comments

@sunny2zhang
Copy link

sunny2zhang commented Mar 24, 2023

我在compent里定义了option
chartOption: EChartsOption = {
title: {
text: '123213',
show: true
},....
}

但在html里无法绑定到 title. Text
<input nz-input name="title" [ngModelOptions]="{ standalone: true }" [(ngModel)]="chartOption.title.text" />

提示的错误信息是
Object is possibly 'undefined'.ngtsc(2532)
chartedit.component.ts(9, 2): Error occurs in the template of component BICharteditComponent.
Property 'text' does not exist on type 'TitleOption | TitleOption[]'.
Property 'text' does not exist on type 'TitleOption[]'.ngtsc(2339)
chartedit.component.ts(9, 2): Error occurs in the template of component BICharteditComponent.
Object is possibly 'undefined'.ngtsc(2532)
chartedit.component.ts(9, 2): Error occurs in the template of component BICharteditComponent.
Property 'text' does not exist on type 'TitleOption | TitleOption[]'.
Property 'text' does not exist on type 'TitleOption[]'.ngtsc(2339)
chartedit.component.ts(9, 2): Error occurs in the template of component BICharteditComponent

@xieziyu
Copy link
Owner

xieziyu commented Mar 25, 2023

Hi @sunny2zhang ,

这个问题有两点需要解决:

  1. 类型不符的问题,这是由于 echarts 本身提供的 EChartsOption 里对 title 的定义是一个 union 类型,其中包含了数组类型的定义,所以在 ngtsc 进行类型推断时产生了错误。可以这样修正:
import { EChartsOption, TitleComponentOption } from 'echarts';


chartOptions: EChartsOption & { title: TitleComponentOption } = {
  1. 双向数据绑定的问题,如果直接将 input 的 ngModelChange 事件绑在 chartOptions.title.text 会由于无法触发 Angular 的 ChangeDetection 导致不会自动更新数据(原因是 ngx-echarts @Input的是整个 options)。所以需要这样实现双向绑定:
<input nz-input name="title" [ngModelOptions]="{ standalone: true }" [ngModel]="chartOption.title.text"  (ngModelChange)="onTitleChange($event)"/>

并在 Component 中添加实现:

onTitleChange(v: string) {
  this.chartOptions = {
    ...this.chartOptions,
    title: {
      text: v
    }
  };
}

希望这有所帮助

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants