Set default value of dropdown in Angular 6

Issue

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

Solution

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.

Answered By – Paresh Gami

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published