【问题标题】:How to match two arrays and change color where an element id matches another id in typescript如何匹配两个数组并更改元素ID与打字稿中的另一个ID匹配的颜色
【发布时间】:2021-11-10 19:59:57
【问题描述】:

我有两个来自 NodeJS MongoDB 和 socket.io 服务器的动态生成的热情数组,我知道来源可能并不重要,但是:

激情1:

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

激情2:

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

使用肉眼可以看出对象{_id: '60a1557f0b4f226732c4597b', name: 'Netflix'} 存在于两个数组中

如何使用现有对象输出或重新创建一个新数组,例如使用 Angular 以粗体显示的 Netflix?

我的代码:

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

任何回答 typescript / JavaScript 都会有很大帮助

提前致谢。

【问题讨论】:

  • 如果我正确理解了您的问题,您基本上希望在name 属性的值与passion 数组中的值匹配时以粗体显示,对吧?
  • @thisdotutkarsh 正确,这正是我需要的

标签: javascript arrays angular typescript ionic-framework


【解决方案1】:

您可以使用NgStyle 指令通过以下方式实现此目的,

在您的 component.html 文件中,

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

在您的 component.ts 文件中, 定义函数getFontWeight,它接受一个字符串类型的参数,如下所示,

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

StackBlitz Demo

【讨论】:

    【解决方案2】:

    最好不要从模板中调用方法,explained here。简而言之,您的模板方法将在每次更改检测时重新运行。

    在 Angular 中,管道是纯粹的,这意味着它们不会重新运行,除非它们的输入发生变化。管道会很简单:

    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);
      }
    }
    

    然后模板将是:

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

    Stackblitz here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      相关资源
      最近更新 更多