[Fixed] how to extract first two characters from an array in html using angular?

Issue

I have a api array object returning value as below:

apival = [{lang: "English",code: "en-ca"}, {lang: "French",code: "fr-ca"}]

I am using this array with ngfor to display the languages in the html. I need to specify a condition to apply some logic. For that, I need a pipe or something which extracts first two characters from the code in runtime.

I know how to split this in typescript. But, I need it in HTML.
In my TS:

currentlang = "en"

In my HTML:

<div*ngfor="let x of apival">
<div*ngIf="x.code == currentlang"></div>
</div>

In the above html code, I need a way to extract the first two characters from the code. Any idea how can I do this?

I dont want to use TS, I can use a pipe or some logic in html

Solution

Yes, using a Pipe it’s the correct way. Try this:

@Pipe({ name: "code" })
export class LangCodePipe implements PipeTransform {
  transform(value: any[], filter?: string): any {
    return value
      .map(lang => {
        return {
          ...lang,
          short: lang.code.split("-")[0]
        };
      })
      .filter(lang => {
        return filter ? filter == lang.short : true;
      });
  }
}

It will contain the logic that you need and also makes the filter optional, the Pipe returns the actual object but also the short code.

Now all you need to do is: declare the pipe in your module and use it in your template.

<!--currentLang is optional param-->
<div *ngFor="let x of apival | code: currentlang">
  {{x | json}}
</div>
<!-- you can also do this -->
<div *ngFor="let x of apival | code">
  {{x | json}}
</div>

Full example here

Leave a Reply

(*) Required, Your email will not be published