点击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
相关产品推荐
相关产品推荐

