0

I have an address object which I am converting into string to display the complete address in the autocomplete. Here's the code.

address.component.html

<mat-form-field class="address-autocomplete">
  <input type="text" placeholder="Legal Address" aria-label="legal address" matInput [formControl]="legalAddress"
    [matAutocomplete]="lglAddress">
  <mat-error *ngIf="legalAddress.invalid">{{ getErrorMessage() }}</mat-error>
  <mat-autocomplete #lglAddress="matAutocomplete" [displayWith]="displayFullAddress">
    <mat-option *ngFor="let address of legalAddresses | async" [value]="address">
      {{ address | addressToString }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

address.component.ts

displayFullAddress(address: Address): string {
  return address ? this._addressService.toString(address) : '';
}

address.service.ts

public toString(address: Address): string {
  const addr1 = address.addressLine1 ? address.addressLine1 + ', ' : '';
  const addr2 = address.addressLine2 ? address.addressLine2 + ', ' : '';
  const addr3 = address.addressLine3 ? address.addressLine3 + ', ' : '';
  const addr4 = address.addressLine4 ? address.addressLine4 + ', ' : '';
  const city = address.addressCity ? address.addressCity + ', ' : '';
  const state = address.addressState ? address.addressState + ', ' : '';
  const postalCode = address.addressPostalCode
    ? address.addressPostalCode + ', '
    : '';
  const country = address.addressCountry ? address.addressCountry : '';

  return `${addr1} ${addr2} ${addr3} ${addr4} ${city} ${state} ${postalCode} ${country}`;
}

I get the the following error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'toString' of undefined TypeError: Cannot read property 'toString' of undefined at MatAutocomplete.displayFullAddress [as displayWith] (main.513c5e2c3c86f0d47f91.js:168958) at MatAutocompleteTrigger._setTriggerValue (main.513c5e2c3c86f0d47f91.js:84813)

If I don't call the toString method from addressService and instead implement the entire logic in the displayFullAddress method, it works fine. Can I not call any other method within a displayWith?

Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72

1 Answers1

2

Figured out that this in this context is bound to mat-autocomplete, that's why it fails. It could be done like this:

displayFullAddress = (address: Address): string => {
  return address ? this._address.toString(address) : null;
}

Here, this is bound to the component and the injected _address service works.

PS: A better explanation to this is provided here

Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72