'angular validation for selecting option from drop down and accordingly inputting next field
I am new to Angular and got stuck in validation.
My problem is that I have dropdown menu with 4 options to select. when user selected one option I want an input field to change validation in such a way that:
If user select option 1 in the drop down than I want in the next input field to have the validation required and maximum length 8 numbers. likewise If the user select option 2 in the drop down. I want the input field to have the validation required and maximum length of 5 number. so i got stuck in validation how to do it. Any help and idea would be greatly appreciated
Solution 1:[1]
html:
<form [formGroup]="selectForm">
<div class="form-group">
<label class="float-left">option</label>
<select class="form-control" (change)="selection($event)" name="select"
id="select" formControlName="select">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="form-group">
<label class="float-left">Input:</label>
<input type="number" class="form-control" formControlName="input">
</div>
</form>
ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from
'@angular/forms';
@Component({
selector: 'app-select',
templateUrl: './select.component.html',
styleUrls: ['./select.component.scss']
})
export class SelectComponent implements OnInit {
}
selectForm:FormGroup;
select:null;
input:any = '';
constructor(
private formBuilder: FormBuilder,
) { }
ngOnInit(): void {
this.createForm();
}
createForm(){
this.selectForm = this.formBuilder.group({
input:["",Validators.required],
})
}
selection(event){
let option = event.target.value;
console.log('id:', option);
this.selectForm.controls['input'].clearValidators();
if (option == "option1") {
this.selectForm.controls['input'].setValidators([
Validators.required,
Validators.maxLength(8),
]);
}
if (option == "option2") {
this.selectForm.controls['input'].setValidators([
Validators.required,
Validators.maxLength(8),
]);
}
if (option == "option3") {
this.selectForm.controls['input'].setValidators([
Validators.required,
Validators.maxLength(8),
]);
}
this.selectForm.updateValueAndValidity();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | danda547 |
