Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having Default Value in Select Option In Reactive Forms

How can i have a default value according to what i already selected before. Like if i edit something and it has a dropdown, i can see the default value that i have submitted before so it won't confused the users. For example, in my code if i click the edit button it would redirect me to the page and would start the "patchValues()" function below and it would able to select from the lists of suppliers. What i want is that if i click the edit button, i can see a default value in the select option

TS

patchValues() {
    let suppliers = this.myForm.get('suppliers') as FormArray;
    this.material.suppliers.forEach(supplier => {
      suppliers.push(this.fb.group({
       supplier_id: supplier.name,
     }))
    })
  }

HTML

<tr *ngFor="let row of myForm.controls.suppliers.controls; let i = index" [formGroupName]="i">
            <td>
              <select formControlName="supplier_id" class="col-md-12" >
                <option *ngFor="let supplier of suppliers"  [value]="supplier.id">
                  {{supplier.name}}
                </option>
              </select>
            </td>
   </tr>
like image 283
Joseph Avatar asked Mar 08 '23 13:03

Joseph


1 Answers

Hopefully I'm understanding your question correctly. You would have a default option, in case that field has no pre value:

<option value="">Select supplier...</option>
<option *ngFor="let supplier of suppliers"  [ngValue]="supplier.id">
  {{supplier.name}}
</option>

and in your patchValues you would seem to want to push the actual id instead of name:

this.material.suppliers.forEach(supplier => {
  suppliers.push(this.fb.group({
   supplier_id: supplier.id
 }))

Now if there is no supplier id, the default option "Select supplier..." would be chosen if the supplier id is an empty string. If it's not an empty string you need to adjust your template accordingly, for example if the value were to be null, you'd want to do:

<option value="null">Select supplier...</option>
like image 141
AT82 Avatar answered Mar 16 '23 03:03

AT82