Angular dropdown validation

后端 未结 2 1686
走了就别回头了
走了就别回头了 2021-01-15 02:03

I\'m using Angular 5 with forms validator. I\'m trying to validate a select dropdown to avoid send the form without the user select an item from the select. The problem is t

2条回答
  •  温柔的废话
    2021-01-15 02:16

    Html:-

    
    
    
    Price Required

    Ts :-

    this.createForm = this.formBuilder.group({ 
       'price':['', [Validators.maxLength(100)],
       'FruitType':['', [Validators.maxLength(100)]
    
    });
    

    when dropdown values changes adding validation for price field.

    this.createForm.controls['FruitType'].valueChanges.subscribe(value => {
      if(value !== '') {
        this.createForm.get('price').setValidators([Validators.required]);
        this.createForm.controls['price'].updateValueAndValidity();
      } else {
        this.createForm.get('price').clearValidators();
        this.createForm.controls['price'].updateValueAndValidity();
      }
     });
    

提交回复
热议问题