1

Im trying to output the address details of the user from backend and to display on html page in an ionic angular project

Here the address details has three fields

Address line1 (mandatory), Address line2 and Address line 3 (non mandatory)

when i try to out these address details in line separated by commas. iam getting extra commas when addressline 2 and 3 are not filled.

i want the commas to shown only if the next two fields are filled else dont want to show

Below is my code.

TS File:

  getAddress() {
this.apiService.getAddress().then(
  res => {
    this.primaryAddrArray = [this.primaryAddress.addressLine1, this.primaryAddress.addressLine2, this.primaryAddress.addressLine3];

  }
}

HTML page:

<h1> Address: </h1>

<p *ngFor="let addr of primaryAddrArray; let i=index">{{addr}}, </p>

because of the comma used after {{addr}} iam getting after each address line.

also tried like this

<h1> Address: </h1>

 <p *ngFor="let addr of primaryAddrArray; let i=index">{{addr} {{primaryAddrArray = null ?  ' ' : ','}} </p>

getting output as

Address:

9th Avenue block,,,

I dont want extra commas if the remaining two address fields are not filled. please assist me on this. thank you.

Shaik
  • 286
  • 2
  • 15
  • 36
  • Not tested but perhaps something like this?: `{{ primaryAddrArray[i + 1] ? ' ' : ',' }} ` – Gynteniuxas Oct 10 '20 at 09:50
  • thanks @Gytis TG for your response, i tried this but getting same. I just required commas for the address fields only if they are filled – Shaik Oct 10 '20 at 10:40
  • Can you provide an example on sandbox server? I would be able to test your case. – Gynteniuxas Oct 10 '20 at 11:07
  • iam newbie to this field and havent tried sandbox server. just running this project in my machine. – Shaik Oct 10 '20 at 11:14

1 Answers1

0

I haven't worked with Angular yet, but I would filter out the empty values in a method. One of the ways is to use the Array.filter() method, which creates a new array with all elements that pass the test implemented by the provided function.

Example:

getAddresses(): string[] {
  return this.primaryAddrArray.filter(function(addr): string {
    return addr !== ''
  })
}

Note that you may also need to check for null values, depending on how you handle empty addresses.

And then in the template, you can do as in Mark Rajcok's answer:

<p *ngFor="let addr of getAddresses(); let isLast=last">{{addr}}{{isLast ? '' : ', '}}</p>
touchmarine
  • 1,548
  • 9
  • 11