You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击editTask按钮时表单中子任务未显示的技术求助

问题解决:编辑任务时子任务未在Angular Material Chip中显示

问题根源

你的代码里有两个关键问题导致子任务不显示:

  • subTasks表单控件初始化为空字符串,而子任务是数组类型,控件类型不匹配
  • 给subTasks赋值时传递的是子任务ID数组,但Chip组件需要的是用于显示的子任务描述文本

解决方案

1. 修正表单控件初始化

在TaskFormComponent的ngOnInit方法里,把subTasks的表单控件初始化为空数组,而非空字符串:

this.taskForm = new FormGroup({
  title: new FormControl(''),
  subTasks: new FormControl([]), // 改为空数组
});

2. 传递正确的子任务显示文本

设置表单值时,将子任务的description(而非id)映射为数组传递给subTasks控件:

if (this.data?.task) {
  this.taskForm.setValue({
    title: this.data.task.title,
    subTasks: this.data.task.subtasks.map((x) => x.description), // 用描述文本替代ID
  });
}

修正后的完整task-form.component.ts代码

export class TaskFormComponent {
  protected readonly Object = Object;
  taskForm!: FormGroup;
  fromPopup = false;
  keywords!: string[];
  @ViewChild(ChipFieldComponent) chipFieldComponent!: ChipFieldComponent;
  
  constructor(
    @Optional()
    @Inject(MAT_DIALOG_DATA)
    public data: { fromPopup: boolean; task: Task }
  ) {}
  
  ngOnInit() {
    this.keywords = [];
    this.fromPopup = !!this.data?.fromPopup;
    this.taskForm = new FormGroup({
      title: new FormControl(''),
      subTasks: new FormControl([]), // 修正初始值为数组
    });
    if (this.data?.task) {
      this.taskForm.setValue({
        title: this.data.task.title,
        subTasks: this.data.task.subtasks.map((x) => x.description), // 传递子任务描述
      });
    }
  }
  
  public get subTasksFormControl() {
    return this.taskForm.get('subTasks') as FormControl;
  }
  
  public onSubmit() {
    console.log('Submitted');
  }
}

额外说明

如果你的ChipFieldComponent在提交时需要传递子任务ID而非描述,可以在组件内部维护“显示文本-ID”的映射关系,或者修改表单结构存储完整的子任务对象,兼顾显示和数据提交需求。

内容的提问来源于stack exchange,提问作者coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 18:42:34