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

Angular组件间传值:如何将Header搜索值传递给CarList组件

Angular跨组件传递搜索值实现产品搜索功能

方法一:使用共享服务(推荐)

当Header和CarList组件无直接父子关系时,共享服务是最灵活的方案,通过RxJS的Observable传递实时数据变化。

1. 创建共享搜索服务

新建search.service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root' // 全局单例注入
})
export class SearchService {
  private searchSubject = new BehaviorSubject<string>('');
  search$: Observable<string> = this.searchSubject.asObservable();

  // 更新搜索字符串
  updateSearchStr(str: string): void {
    this.searchSubject.next(str);
  }
}

2. 修改Header组件

  • 注入搜索服务,绑定输入框事件实时更新搜索值
  • header.component.ts修改:
import { Component, OnInit } from '@angular/core';
import { SearchService } from '../search.service'; // 注意路径匹配

export class HeaderComponent implements OnInit {
  searchStr: string = '';

  constructor(private searchService: SearchService) { }

  ngOnInit(): void {
  }

  onSearchInput(): void {
    this.searchService.updateSearchStr(this.searchStr);
  }
}
  • header.component.html修改(需确保模块导入FormsModule):
<form class="d-flex me-5">
    <input 
      type="text" 
      class="form-control me-2" 
      placeholder="Search cars..."
      [(ngModel)]="searchStr"
      (ngModelChange)="onSearchInput()"
    >
</form>

3. 修改CarList组件

  • 注入搜索服务,订阅搜索值变化;可选使用async管道避免手动取消订阅

方式1:手动管理订阅

import { Component, OnInit, OnDestroy } from '@angular/core';
import { SearchService } from '../search.service';
import { Subscription } from 'rxjs';

export class CarListComponent implements OnInit, OnDestroy {
  cars: any[] = []; // 你的产品数组
  pageNumber = 6;
  currentPg = 1;
  searchStr: string = '';
  private searchSubscription!: Subscription;

  constructor(private searchService: SearchService) { }

  ngOnInit(): void {
    this.searchSubscription = this.searchService.search$.subscribe(str => {
      this.searchStr = str;
      // 可选:搜索时重置分页
      // this.currentPg = 1;
    });
  }

  ngOnDestroy(): void {
    this.searchSubscription.unsubscribe();
  }
}

方式2:使用async管道(无需手动取消订阅)

import { Component, OnInit } from '@angular/core';
import { SearchService } from '../search.service';
import { Observable } from 'rxjs';

export class CarListComponent implements OnInit {
  cars: any[] = [];
  pageNumber = 6;
  currentPg = 1;
  search$: Observable<string>;

  constructor(private searchService: SearchService) { 
    this.search$ = this.searchService.search$;
  }

  ngOnInit(): void {
  }
}

模板修改为:

<div *ngFor="let car of cars | paginate: { itemsPerPage: pageNumber, currentPage: currentPg} | search:(search$ | async)" class="col-md-3">
  <!-- 原有内容保持不变 -->
</div>

方法二:通过共同父组件传递(适用于有共同父组件的场景)

如果Header和CarList同属一个父组件(如AppComponent),可通过@Output和@Input传递数据:

1. Header组件添加@Output事件

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

export class HeaderComponent implements OnInit {
  searchStr: string = '';
  @Output() searchChange = new EventEmitter<string>();

  constructor() { }

  ngOnInit(): void {
  }

  onSearchInput(): void {
    this.searchChange.emit(this.searchStr);
  }
}

2. 父组件中转数据

父组件模板:

<app-header (searchChange)="onSearchChange($event)"></app-header>
<app-car-list [searchStr]="currentSearchStr"></app-car-list>

父组件ts:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  currentSearchStr: string = '';

  onSearchChange(str: string): void {
    this.currentSearchStr = str;
  }
}

3. CarList组件添加@Input接收值

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

export class CarListComponent implements OnInit {
  cars: any[] = [];
  pageNumber = 6;
  currentPg = 1;
  @Input() searchStr: string = '';

  constructor() { }

  ngOnInit(): void {
  }
}

补充:优化SearchPipe

完善管道处理空值和大小写不敏感搜索:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(cars: any[], value: string): any[] {
    if (!cars || !value) return cars; // 空值返回原数组
    const lowerValue = value.toLowerCase();
    return cars.filter(car => 
      car.name.toLowerCase().includes(lowerValue)
    );
  }
}

内容的提问来源于stack exchange,提问作者Jana Jasinovski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:20:33