简体   繁体   English

如何从角度6的FormGroup中重置特定控件

[英]How to reset particular controls from FormGroup in angular 6

I am using FormGroup to take data from Frond end after submitting the form usually .reset() the method will reset all values from Controls. 我通常在提交表单后使用FormGroupFormGroup端获取数据.reset()方法将重置Controls中的所有值。

1) I have five FormControls on my page but I want only to reset only 4 option, remaining 1 should be disabled with its already selected value. 1)我的页面上有五个FormControl,但是我只想重设4个选项,其余1个应使用其已选择的值禁用。

2) Want to get rid of that Red-line (Error Class) which UI looks like: 2)希望摆脱UI看起来像这样的红线(错误类):

在此处输入图片说明

What I have tried so far (If the formControl name is brand then disable): 到目前为止,我已经尝试过(如果formControl名称是brand则禁用):

ResetControls() method: ResetControls()方法:

  for (var name in this.form.controls) {
      if (name != 'brand') {
        this.form.reset();
        (<FormControl>this.form.controls[name]).setValidators(Validators.compose([]))
        this.form.controls[name].setErrors(null);
      }
      else
      {
       // var value = (<FormControl>this.form.controls[name]).value;
        (<FormControl>this.form.controls[name]).markAsPristine();
        (<FormControl>this.form.controls[name]).markAsUntouched();
       this.form.get('brand').disable();  

      }
    }

FormGroup: 表格组:

this.form = new FormGroup({
      brand: new FormControl("", Validators.compose([
        Validators.required,
      ])),
      sku: new FormControl("", Validators.compose([
        Validators.required,
      ])),
      cRate: new FormControl("", Validators.compose([
        Validators.required,
      ])),
      pRate: new FormControl("", Validators.compose([
        Validators.required,
      ])),
      eDate: new FormControl("", Validators.compose([
        Validators.required,
      ])),
    });

3) Which reset all the option but unable to apply existing required field for every Control. 3)重置所有选项,但无法为每个控件应用现有的必填字段。

You have to pass in the map of states that matches the form controls in your form. 您必须传递与表单中的表单控件匹配的状态图。

const form = new FormGroup({

first: new FormControl('first name'),
  last: new FormControl('last name')
});

form.reset({
  first: {value: 'name', disabled: true},
  last: 'last'
});

console.log(this.form.value);  // {first: 'name', last: 'last name'}
console.log(this.form.get('first').status);  // 'DISABLED'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM