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

咨询Angular组件间数据传递方法,含非父子场景及示例代码需求

Angular组件间数据传递方案

一、父子组件间传递

1. 父传子(@Input)

父组件通过模板绑定属性传递数据,子组件用@Input装饰器接收。

示例代码:
父组件模板:

<app-child [parentData]="parentValue"></app-child>

父组件类:

parentValue = '来自父组件的数据';

子组件类:

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

export class ChildComponent {
  @Input() parentData!: string;
}

2. 子传父(@Output + EventEmitter)

子组件定义事件发射器,触发时传递数据,父组件监听事件接收数据。

示例代码:
子组件类:

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

export class ChildComponent {
  @Output() childDataEvent = new EventEmitter<string>();

  sendDataToParent() {
    this.childDataEvent.emit('来自子组件的数据');
  }
}

父组件模板:

<app-child (childDataEvent)="handleChildData($event)"></app-child>

父组件类:

handleChildData(data: string) {
  console.log(data); // 输出:来自子组件的数据
}

二、非父子组件间传递

1. 共享Service(BehaviorSubject)

通过创建全局共享服务,结合RxJS的BehaviorSubject实现数据的发布与订阅,适合跨层级、无关联组件传值。

示例代码:
共享服务:

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

@Injectable({ providedIn: 'root' })
export class DataShareService {
  private dataSubject = new BehaviorSubject<string>('初始数据');
  currentData = this.dataSubject.asObservable();

  updateData(newData: string) {
    this.dataSubject.next(newData);
  }
}

发布数据的组件:

import { DataShareService } from './data-share.service';

export class ComponentA {
  constructor(private dataService: DataShareService) {}

  sendData() {
    this.dataService.updateData('来自组件A的数据');
  }
}

订阅数据的组件:

import { DataShareService } from './data-share.service';
import { Subscription } from 'rxjs';

export class ComponentB {
  receivedData!: string;
  private subscription!: Subscription;

  constructor(private dataService: DataShareService) {}

  ngOnInit() {
    this.subscription = this.dataService.currentData.subscribe(data => {
      this.receivedData = data;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe(); // 销毁时取消订阅,避免内存泄漏
  }
}

2. 路由参数传递

组件通过路由跳转时,可通过路由参数传递数据,适合页面跳转场景。

示例代码:
路由配置:

const routes: Routes = [
  { path: 'target/:id', component: TargetComponent }
];

发起跳转的组件:

import { Router } from '@angular/router';

export class SourceComponent {
  constructor(private router: Router) {}

  navigateWithData() {
    this.router.navigate(['/target', '123']); // 传递id参数
  }
}

接收参数的组件:

import { ActivatedRoute } from '@angular/router';

export class TargetComponent {
  id!: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    // 快照获取参数(适合参数不变化的场景)
    this.id = this.route.snapshot.paramMap.get('id')!;
    // 订阅参数变化(适合路由复用场景)
    this.route.paramMap.subscribe(params => {
      this.id = params.get('id')!;
    });
  }
}

3. ViewChild/ContentChild

父组件通过ViewChild获取子组件实例,直接访问子组件的属性或调用方法,仅限父子关联的组件使用。

示例代码:
父组件类:

import { ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

export class ParentComponent implements AfterViewInit {
  @ViewChild(ChildComponent) childComponent!: ChildComponent;

  ngAfterViewInit() {
    console.log(this.childComponent.childValue); // 访问子组件属性
    this.childComponent.childMethod(); // 调用子组件方法
  }
}

子组件类:

export class ChildComponent {
  childValue = '子组件的属性值';

  childMethod() {
    console.log('子组件方法被调用');
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:46:13