Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value of dropdown in Angular 6

I am populating DropDown using service. service returns simple Array of key/value pair.

TypeScript:

public initializeForm(): void {
        this.form = this.fb.group({
            supplierId: ["", [Validators.required]],
            username: ["", Validators.required],
            credentials: ["", [Validators.required]],
            rating: [""]
        })
    }


this.adminService.getSuppliers({ active: "true" }).subscribe(res => {
    this.suppliers = res;
})

HTML:

<select class="form-control" formControlName="supplierId">
     <option>Select Supplier</option>
     <option *ngFor="let s of suppliers" [value]="s.supplierId">{{s.supplierName}}</option>
</select>

As you can see in below image, default option is not set as selected option on page load. I want default option to be selected on page load same like simple HTML and fires required field validation when I try to submit page by selecting default option in dropdown

enter image description here

UPDATED:
If i set default option value to 0, it doesn't support required validation and consider as valid if I select default option

like image 292
Ubiquitous Developers Avatar asked Dec 18 '22 17:12

Ubiquitous Developers


1 Answers

Set validation.min with required as well like below one.

supplierId: ["", [Validators.required, Validators.min(1)]]

supplierId is always greater zero so min(1) works for you.

like image 120
Paresh Gami Avatar answered Dec 28 '22 11:12

Paresh Gami