Search code examples
angularangular-materialangular2-formsangular9ngmodel

select autocomplete set value ngModel programmatically on edit form


When I get to the edit form I need to prefill the values to the form.

the create form works fine and the values are submitted fine,

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>

I use the [displayWith]="customerCollectionDisplayFn" to display the value to the input

TS:

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

Solution

  • So What I did I just changed the ngModel [ngModel]="customer" then

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

    and it got up..

    --- BONUS ---

    for a select input, this worked

    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>
    

    the CODE

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