установить значение по умолчанию для опции Выбрать в angular форме обновления - PullRequest
0 голосов
/ 31 марта 2020

Я работаю над задачей обновления, у меня есть список объектов, отображаемых в виде данных, и я хочу выполнить процесс обновления с модальной формой, содержащей форму ввода и выбрать параметры, когда нажимаю кнопку, чтобы отобразить форму вход принимает первый атрибут моего objectn, но проблема в том, что опция select не принимает значение по умолчанию, которое должно быть вторым атрибутом объекта!

<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
    })
  }


}

Это делает работу и отображает президентов в выпадающем списке. Однако мне также нужно выбрать президента объекта для обновления по умолчанию.

1 Ответ

0 голосов
/ 31 марта 2020

Попробуйте это:

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

В соответствии с внутренним шаблоном вашего условия, вы сравниваете опцию с null. Но значение по умолчанию для formControl ''.

...