【问题标题】:Why is Angular8 form.status VALID when input fields are blank?为什么输入字段为空白时Angular8 form.status VALID?
【发布时间】:2020-08-27 18:06:26
【问题描述】:

组件如下:

  export class SchedulerComponent implements OnInit {

  schedulerForm : FormGroup;
  constructor(private fb: FormBuilder,
              private schedulerReportService: SchedulerReportService) { 

    this.prefReport="dayReport";
    this.schedulerForm = this.fb.group({
      schedulerCategory:['dayReport'],
      dayReport: this.fb.group({
        d_date: ['',Validators.required],
        d_runTime: ['',Validators.required],
        d_timeZone: ['',Validators.required],
      }),
      rangeReport: this.fb.group({
        r_runTime: [''],
        r_startDate: [''],
        r_endDate: [''],
        r_timeZone: ['']
      }),
    });
    this.onValueChanges()

  }
  @Output() change: EventEmitter<MatRadioChange>; 
  @Output() scheduleEvent = new EventEmitter<ScheduleService>();

  showScheduler = false
  prefReport : string

  dayReport = true;
  rangeReport = false;

  ngOnInit() {

    this.setScheduleFormValidators();
  }

  onValueChanges(): void {

    this.schedulerForm.valueChanges.subscribe(val=>{

     console.log(this.schedulerForm.status)
     if(this.schedulerForm.status === 'VALID'){

      let scheduleServiceModel = new ScheduleService(val)
      this.scheduleEvent.emit(scheduleServiceModel)
      } 
    })
  }


  toggled(){
    this.showScheduler = !this.showScheduler;

  }

  radioSelect(event : MatRadioChange){

    let radioSelect=event.value;
    this.schedulerForm.reset();
    if (radioSelect == 'dayReport'){
      this.dayReport = true;
      this.rangeReport = false;
      this.schedulerForm.get('schedulerCategory').setValue('dayReport');
    }else if(radioSelect == 'rangeReport'){
      this.dayReport = false;
      this.rangeReport = true;
      this.schedulerForm.get('schedulerCategory').setValue('rangeReport');

    }
  };

  setScheduleFormValidators() : void {
    const drunTime = this.schedulerForm.get(['dayReport','d_runTime']);
    const ddate = this.schedulerForm.get(['dayReport','d_date']);
    const dtimeZone = this.schedulerForm.get(['dayReport','d_timeZone']);

    const rrunTime = this.schedulerForm.get(['rangeReport','r_runTime']);
    const rtimeZone = this.schedulerForm.get(['rangeReport','r_timeZone']);
    const rstartDate = this.schedulerForm.get(['rangeReport','r_startDate']);
    const rendDate = this.schedulerForm.get(['rangeReport','r_endDate']);

    this.schedulerForm.get('schedulerCategory').valueChanges
    .subscribe(schedulerCategory => {
      if (schedulerCategory === 'dayReport') {
        drunTime.setValidators([Validators.required]);
        ddate.setValidators([Validators.required]);
        dtimeZone.setValidators([Validators.required]);
        rrunTime.setValidators(null);
        rtimeZone.setValidators(null);
        rstartDate.setValidators(null);
        rendDate.setValidators(null);
      }
      else if (schedulerCategory === 'rangeReport') {
        drunTime.setValidators(null);
        ddate.setValidators(null);
        dtimeZone.setValidators(null);
        rrunTime.setValidators([Validators.required]);
        rtimeZone.setValidators([Validators.required]);
        rstartDate.setValidators([Validators.required]);
        rendDate.setValidators([Validators.required]);

      }
      drunTime.updateValueAndValidity();
      ddate.updateValueAndValidity();       
      dtimeZone.updateValueAndValidity();
      rrunTime.updateValueAndValidity();
      rtimeZone.updateValueAndValidity();
      rstartDate.updateValueAndValidity();
      rendDate.updateValueAndValidity();

    });

  }

}

当 radioSelect() 函数被触发时,会向用户显示一个表单组。现在,当我运行应用程序并完成预先选择的表单时,一切都很好。但是,如果我切换 radioSelect() 我在控制台中收到此行为/错误,则状态无效,直到 scheduleCategory 更新(但这只是其中一个字段):

scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 VALID

我正在收听表单上的值更改,在切换到它之后,没有填写任何字段,form.valueChanges 订阅者向我们显示 form.status 是有效的,我在这里遗漏了一些东西,我无法确定它。非常感谢您的见解!

【问题讨论】:

  • 为什么不“禁用”FormControls?禁用的 FormControl 始终有效
  • 我觉得我没听懂,你能解释一下吗?
  • 啊,谢谢@Eliseo 的澄清

标签: angular typescript validation angular8 angular-reactive-forms


【解决方案1】:

通常我用 .valid 和 .dirty 过滤 valueChanges

myForm.valueChanges.pipe(
   filter(() => myForm.valid && myForm.dirty)
   )
.subscribe(values => ...

【讨论】:

  • 在这种情况下使用管道比订阅有优势吗?
  • 谢谢伙计,优雅的回答,一定会读到肮脏和原始的:)
猜你喜欢
  • 2015-06-15
  • 1970-01-01
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 2023-03-18
  • 1970-01-01
  • 2016-08-03
相关资源
最近更新 更多