программно выбрать значение автозаполнения ngModel в форме редактирования - PullRequest
0 голосов
/ 27 мая 2020

Когда я перехожу к форме редактирования, мне нужно предварительно заполнить значения формы.

форма создания работает нормально, и значения отправляются нормально,

HTML:

<!-- customers-->
<div class="col-md-6">
  <mat-form-field class="example-full-width">
    <input type="text"
           placeholder="Customers"
           i18n-placeholder="customerInput"
           aria-label="customers"
           matInput
           required
           [name]="'customerId'"
           (focus)="getCustomers(searchedCustomer)"
           [ngModel]="contractInterface.customerName"
           (ngModelChange)="customerOnChange($event)"
           [matAutocomplete]="autoCustomer">
    <mat-autocomplete #autoCustomer="matAutocomplete" [displayWith]="customerCollectionDisplayFn">

      <mat-option *ngIf="customerloading"><span [ngTemplateOutlet]="loading"></span></mat-option>

      <ng-container *ngIf="!customerloading">
        <mat-option *ngFor="let customer of customerList" [value]="customer">
          {{ customer.name }}
        </mat-option>
      </ng-container>
    </mat-autocomplete>
  </mat-form-field>
</div>

Я использую [displayWith]="customerCollectionDisplayFn" для отображения значения на входе

TS:

  customerCollectionDisplayFn(customer?) {
return customer?.name;
}

Ответы [ 2 ]

0 голосов
/ 27 мая 2020

Итак, что я сделал, я просто изменил ngModel [ngModel]="customer", затем

  private getContractDetails(id: number) {

    this.contractService.loadContractDetails(id)
      .subscribe( (rez: Contract) => {
        // add value to customer input
        this.customer.name = rez.customerName; // <-- this

и он встал ..

--- БОНУС ---

для выбранного входа это сработало

HTML:

 <mat-form-field>
        <mat-label i18n="@@typeInput">Type</mat-label>
        <mat-select
          name="typeId"
          [ngModel]="typesVal" // <--- this
          (ngModelChange)="setContractType($event)"
          #item="ngModel">
          <mat-option *ngIf="isLoadingTypes"><span [ngTemplateOutlet]="loading"></span></mat-option>
          <ng-container *ngIf="!isLoadingTypes">
            <mat-option>None</mat-option>
            <mat-option *ngFor="let item of contractTypeList" [value]="item">{{ item.name }}</mat-option>
          </ng-container>
        </mat-select>
      </mat-form-field>

КОД

this.typesVal = this.contractTypeList.find(x => x.id === rez.typeId);

0 голосов
/ 27 мая 2020
    1. When you click the "Edit Form" Button you have to gather the persisted 
information for the form inputs fields. this might be from localstorage or from 
http request via angular service ([Angular Tutorial Http Server][1]) like in 
section --> "app/config/config.service.ts (getConfig v.1)".


    2. then create an empty "contractInterface" property in your component and 
update it after you got the infos from localstorage or http request


    like ...
    contractInterface: any = {};

    or ...
    contractInterface: BlaInterface = new BlaInterface();

    later...

    loadMyFormValues() {
      this.myFormService.myGetFormValuesFn()
        .subscribe((contractInterface: any) 
        => this.contractInterface = contractInterface);
    }


      [1]: https://angular.io/guide/http#requesting-data-from-a-server

ps: использование слова interface в имени переменной может сбивать с толку. лично я предпочитаю избегать этого. также в самом названии интерфейса, если применимо.

...