gpt4 book ai didi

angular - 需要垫选择不能重置

转载 作者:太空狗 更新时间:2023-10-29 18:28:28 24 4
gpt4 key购买 nike

每个使用 mat-select 作为唯一必填字段的 formGroup 不能用 FormGroup.reset() 重置,因为验证器没有重置

https://stackblitz.com/edit/material7-template-matselect-required?file=src%2Fapp%2Fapp.component.html

提交时,第一个字段为空并标记为错误...

唯一对我有用的解决方案是使用 ngIf 来重新生成表单,但对于看到空 html 的用户来说并不是很好......

还有其他解决方案吗?

谢谢!

最佳答案

由于已经有一个可接受的答案,我可以建议少加几行。

这是 Material 的一个众所周知的错误,作为解决方法,您可以将 ElementReference 添加到您的 form 标记 #f="ngForm":

<form [formGroup]="quickFileForm" (ngSubmit)="saveQuickFileForm()" #f="ngForm">

然后将 @ViewChild 装饰器添加到您的 TS 部分,以引用您表单中的标签:

import { Component, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
group = new FormGroup({
select: new FormControl(null, Validators.required),
input: new FormControl()
});

@ViewChild('f') myForm;

....
....
}

不要忘记从 @angular/core 导入它。然后只需添加:

this.myForm.resetForm();

你的方法:

submit() {
if(this.group.valid) {
const obj = new MyObj();
Object.assign(obj, this.group.value);

this.survey.push(obj);
this.myForm.resetForm(); // <-- Here you add it.
return;
}

alert('not valid, try again')
}

关于angular - 需要垫选择不能重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53522364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com