Search code examples
htmlangularselectdata-binding

set default value of Select option in angular update form


I'm working on an update task, I have a list of objects displayed in datatable and I want to execute the update process with a modal contain a form with an input and select options, when click the button to display the form, the input take the first attribute of my objectn but the problem is that the select option does not take a default value which is should be the second attribute of object !

<a data-toggle="modal" [attr.data-target]="'#modal-centered' + index"><i class="la la-pencil edit"
                      (click)="patchValue(rowData)"></i></a>
                  <div [attr.id]="'modal-centered' + index" class="modal fade">
                    <div class="modal-dialog modal-dialog-centered">
                      <div class="modal-content">
                        <div class="modal-header">
                          <h4 class="modal-title">{{rowData.name}}</h4>
                          <button type="button" class="close" data-dismiss="modal">
                            <span aria-hidden="true">×</span>
                            <span class="sr-only">Fermer</span>
                          </button>
                        </div>
                        <div class="modal-body">
                          <form [formGroup]="updateForm">
                            <div class="form-group">
                              <input type="text" formControlName="name" placeholder="Nom de la commission"
                                class="form-control">
                            </div>
                            <div class="form-group">
                              <select name="president" class="col-lg-6 custom-select form-control rounded"
                                formControlName="president">
                                <option [ngValue]="null" disabled>Choisir un Président</option>
                                <option [value]="president._id" *ngFor="let president of presidents">
                                  {{president.firstName}}
                                  {{president.lastName}}</option>
                              </select>
                            </div>
                          </form>
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-primary" data-dismiss="modal"
                            (click)="updateCommission(rowData._id)">Sauvegarder</button>
                        </div>
                      </div>
                    </div>
                  </div>

import { Component, OnInit } from '@angular/core';

import { HttpClient } from '@angular/common/http';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-commission',
  templateUrl: './commission.component.html',
  styleUrls: ['./commission.component.css']
})
export class CommissionComponent implements OnInit {
  commissions: any[];
  updateForm: FormGroup;

  presidents: any[];

  cols: any[];
  loading: boolean = true;

  constructor(
    private http: HttpClient
  ) {
    this.updateForm = new FormGroup({
      name: new FormControl(''),
      president: new FormControl('')
    });
  }

  ngOnInit() {

    this.http.get('/api/commissions').subscribe((commissions: any[]) => {
      this.loading = false
      this.commissions = commissions;
    })

    this.http.get('/api/users/byType/conseillerMunicipal').subscribe((presidents: any[]) => {
      this.presidents = presidents;
    })

    this.cols = [
      { field: 'name', header: 'Nom' },
      { field: 'presidentFullName', header: 'President' },
    ];
  }



  updateCommission(commissionID) {
    this.loading = true;
    this.http.put('/api/commissions/' + commissionID, this.updateForm.value).subscribe(updatedCommission => {
      this.loading = false;
      this.commissions.filter(commission => commission._id === commissionID)[0] = updatedCommission;
    })
  }


  patchValue(commission) {
    debugger
    this.updateForm.setValue({
      name: commission.name,
      president: commission.presidentFullName
    })
  }


}

This does the job and displays the presidents in a drop down. However, I also need to select the president of the object to updated by default .


Solution

  • Try this one:

    this.updateForm = new FormGroup({
      name: new FormControl(''),
      president: new FormControl(null)
    });
    

    Accoring to your condition inner template, you compare option with null. But your default value for formControl is ''.