You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript/Angular匹配双数组并对ID匹配元素设置高亮样式的方法

实现方案

首先我们先在组件逻辑层提取两个数组的公共ID集合,用Set存储可以大幅提升判断效率,避免每次渲染都遍历第二个数组。

第一步:TypeScript 组件逻辑

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-passion-list',
  templateUrl: './passion-list.component.html',
  styleUrls: ['./passion-list.component.css']
})
export class PassionListComponent implements OnInit {
  // 原始数据
  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'}
  ];

  // 存储公共兴趣的ID集合
  commonPassionIds = new Set<string>();

  ngOnInit(): void {
    // 提取passions2的所有ID存入Set
    this.passions2.forEach(passion => {
      this.commonPassionIds.add(passion._id);
    });
  }
}

第二步:模板渲染

直接在模板中判断当前兴趣ID是否在公共集合中,是就加粗显示:

<div *ngFor="let passion of passions1">
  <span *ngIf="!commonPassionIds.has(passion._id)">{{passion.name}}</span>
  <strong *ngIf="commonPassionIds.has(passion._id)">{{passion.name}}</strong>
</div>

扩展方案:合并两个数组所有兴趣展示

如果你需要把两个数组的所有兴趣合并去重后展示,同时给公共项加粗,可以调整逻辑如下:

// 组件类中新增合并后的数组
mergedPassions: Array<{_id: string, name: string, isCommon: boolean}> = [];

ngOnInit(): void {
  const allPassions = [...this.passions1, ...this.passions2];
  const idMap = new Map<string, {_id: string, name: string, isCommon: boolean}>();

  // 先收集两个数组的ID集合
  const p1Ids = new Set(this.passions1.map(p => p._id));
  const p2Ids = new Set(this.passions2.map(p => p._id));

  allPassions.forEach(passion => {
    if (!idMap.has(passion._id)) {
      idMap.set(passion._id, {
        ...passion,
        // 判断是否是两个数组共有的
        isCommon: p1Ids.has(passion._id) && p2Ids.has(passion._id)
      })
    }
  })

  this.mergedPassions = Array.from(idMap.values());
}

模板代码:

<div *ngFor="let passion of mergedPassions">
  <span [style.fontWeight]="passion.isCommon ? 'bold' : 'normal'">{{passion.name}}</span>
</div>

内容的提问来源于stack exchange,提问作者Lexacle Technologies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:57:03