Home > Mobile >  How to match two arrays and change color where an element id matches another id in typescript
How to match two arrays and change color where an element id matches another id in typescript

Time:09-16

I have two dynamically generated passion arrays from NodeJS MongoDB and socket.io server and I know the source may not be important but:

passions1:

[{_id: '60a1557f0b4f226732c4597b', name: 'Netflix'},
{_id: '60a1557f0b4f226732c45980', name: 'Music'},
{_id: '60a1557f0b4f226732c45991', name: 'Hiking'}]

passions2:

[{_id: '60a4457fr54646647888876d', name: 'Cooking'},
{_id: '60a1557f0b4f226732c4597b', name: 'Netflix'},
{_id: '60a1557f0b4f226732c45997', name: 'Swimming'}]

Using naked eyes one can tell that the object {_id: '60a1557f0b4f226732c4597b', name: 'Netflix'} exists on both arrays

How do you output or recreate a new array with the existing objects e.g Netflix in bold using angular?

My code:

<div *ngFor="let passion of passions1">
<span>{{passion.name}}<span>
<!--
I'm stuck here ..... 
<span *ngIf="passion.name === passion[]">{{passion.name}}<span>
 -->
</div>

Any answer typescript / JavaScript would be of great help

Thanks in advance.

CodePudding user response:

It's better for Angular performance to not call methods from the template, explained here. In short, your template method is going to be re-run on every change detection.

In Angular, Pipes are pure, meaning they don't get re-run unless their inputs change. The pipe would be pretty simple:

import {
  Pipe,
  PipeTransform
} from '@angular/core';
interface PassionObj {
  _id: string;
  name: string;
}

@Pipe({
  name: 'boldCommonInterests'
})
export class BoldCommonInterestsPipe implements PipeTransform {
  transform(passion: string, passion2Arr: PassionObj[]): boolean {
    return passion2Arr.some(el => el.name === passion);
  }
}

And then the template would be:

<div *ngFor="let passion of passions1">
  <span [class.bold-passion]="passion.name | boldCommonInterests: passions2"
    >{{passion.name}}
  </span>
</div>

Stackblitz here.

CodePudding user response:

You can use the NgStyle directive for achieving this in the following way,

In your component.html file,

<div *ngFor="let passion of passionObject">
    <span [ngStyle]="{'font-weight': getFontWeight(passion.name)}">{{passion.name}}</span>
</div>

In your component.ts file, define function getFontWeight that accepts a single parameter of type string as follows,

getFontWeight(passionName) {
    for (let i = 0; i < this.arrayOfPassions.length; i  ) {
      if (passionName === this.arrayOfPassions[i]['name']) {
        return 'bold';
      }
    }
    return 'normal';
  }

StackBlitz Demo

  • Related