Search code examples
angulardata-bindingangular-materialangular7two-way-binding

How can bind angular material auto complete data in component


below screenshoot is showing two things CODE and CompositionDescription if i select description i have to save its code in db how could i??I am working on Project . Using angular material auto-complete.Its working accurately.My problem is that i want to bind data while i select specific data from list but i don't know how to bind it.

i tried [(ngModel)] but all in vain

.html Code

<mat-form-field class="four-full-width">
  <input type="text" placeholder="Shipment Type" 
     [(ngModel)]="contractvm.shipmenttype" aria-label="Number" matInput 
     [formControl]="myControl1" [matAutocomplete]="auto1">
  <mat-autocomplete #auto1="matAutocomplete" >
   <mat-option *ngFor="let option of filterContractShipmentTypetLov | async" 
     [value]="option">{{option}}
   </mat-option>
  </mat-autocomplete>
</mat-form-field>

.ts file code

getContractShipmenttypelov(){    
    this.apiService.getContractShipmenttypelov().subscribe(data =>{
      console.log('getContractShipmenttypelov',data);      
      this.lstContractShipmenttypeDbValue = new Array();
      for (let item of data) {  
        var singleitem: any;
        singleitem = new PortLov();
        singleitem.SHIPMENTTYPEDESCRIPTION = item.SHIPMENTTYPEDESCRIPTION;        this.lstContractShipmenttypeDbValue.push(singleitem.SHIPMENTTYPEDESCRIPTION);} this.filterContractShipmentTypetLov = this.myControl1.valueChanges
.pipe(startWith(''),(value => this.filtershipmenttype(value)));})
}

Solution

  • try add "(optionSelected)" and check inside your component file that what is happening

    <mat-form-field class="four-full-width">
     <input type="text" placeholder="Shipment Type" 
       [(ngModel)]="contractvm.shipmenttype" aria-label="Number" matInput 
       [formControl]="myControl1" [matAutocomplete]="auto1">
     <mat-autocomplete #auto1="matAutocomplete" 
      ***(optionSelected)="onOptionSelected($event)"***>
     <mat-option *ngFor="let option of filterContractShipmentTypetLov | async" 
       [value]="option">{{option}}
     </mat-option>
    </mat-autocomplete>
    </mat-form-field>
    

    -----------------------TS File add event and check what is happening when you select an item

        onOptionSelected(dataOption: any) {
              console.log(dataOption.option.value);
         //set you model here so that your input box get selected value
         }