【问题标题】:Conditional field validation in Angular 6+ depending on value of select fieldAngular 6+中的条件字段验证取决于选择字段的值
【发布时间】:2019-01-29 17:30:56
【问题描述】:

我正在尝试执行仅对选择框的某些值所需的可选字段。我以为我很接近,但在验证时未填充该值。

requiredForTypeValidator = 
    (values) => 
        (control: any): {[key: string]: boolean} | null => {

    const ticket_type = control.parent ? control.parent.value.type : '';
    if (control.value !== undefined && ((control.value === null || control.value.length < 1) && values.indexOf(ticket_type) !== -1)) {
        return {'required': true};
    }
    return null;
}

 ngOnInit() {
    this.createTicketForm = this.formBuilder.group({
        type: [null, Validators.required],
        optField: [null, this.requiredForTypeValidator(['validate_me','validate_me_too'])],
    });
 }

根据要求,我在 stackblitz 重新创建了这个问题: https://stackblitz.com/edit/angular-nt8hjw

【问题讨论】:

标签: angular forms validation


【解决方案1】:

这里有解决问题的有效方法stackblitz

基本上,我创建了一个新函数,它订阅下拉更改并更新依赖字段的验证器。

private setValidators(): void {
    this.createTicketForm.get('type').valueChanges.subscribe(
    (result) => {
      if ( result ==='Check me') {
        this.createTicketForm.get('optField').setValidators(Validators.required);
        console.log('validator set');
      } else {
        this.createTicketForm.get('optField').setValidators(null);
      }
      this.createTicketForm.get('optField').updateValueAndValidity();
    }
   );
}

【讨论】:

    猜你喜欢
    • 2012-05-23
    • 2019-02-05
    • 2021-08-28
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2014-08-17
    相关资源
    最近更新 更多