Angular中如何通过@Input/@Output实现msg与filter同级组件传值?
Angular同级兄弟组件传值解决方案
问题原因
你的msg组件和filter组件属于同一父组件下的同级兄弟组件,无法直接通过@Input或@Output完成跨组件传值,需要通过父组件作为中转,或者使用共享服务实现。现有代码的核心错误是混淆了Angular的属性绑定([],父传子)和事件绑定((),子传父)的用法。
方案1:父组件中转(推荐轻量场景)
步骤1:修改msg.component.ts,通过@Output向父组件抛值
// 导入所需装饰器 import { Component, Output, EventEmitter, OnInit } from '@angular/core'; @Component({ selector: 'app-msg', templateUrl: './msg.component.html' }) export class MsgComponent implements OnInit { msg: string = 'text from msg component'; // 定义输出事件,用于向父组件传递数据 @Output() msgEmit = new EventEmitter<string>(); ngOnInit() { // 组件初始化时推送msg数据,若msg后续动态变化,变化时再次调用emit即可 this.msgEmit.emit(this.msg); } }
步骤2:修改main.component.ts,定义变量存储msg组件传递的值
import { Component } from '@angular/core'; @Component({ selector: 'app-main', templateUrl: './main.component.html' }) export class MainComponent { // 中转存储msg组件传过来的值 receivedMsg: string = ''; }
步骤3:修改main.component.html,完成父子间的绑定逻辑
<!-- 绑定msg组件的输出事件,接收数据存入父组件变量 --> <app-msg (msgEmit)="receivedMsg = $event"></app-msg> <!-- 通过属性绑定,把中转值传给filter组件 --> <app-filter [filterMsg]="receivedMsg"></app-filter>
步骤4:修改filter.component.ts,通过@Input接收父组件传值
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-filter', templateUrl: './filter.component.html' }) export class FilterComponent { // 加@Input装饰器,标识该属性可由父组件传入值 @Input() filterMsg: string = ''; }
方案2:共享服务(推荐多组件传值/跨层级传值场景)
如果项目中传值场景多,无需父组件中转,直接通过全局共享服务+RxJS订阅实现:
1. 创建共享服务shared.service.ts
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; @Injectable({ providedIn: 'root' // 全局单例 }) export class SharedService { // 用Subject做消息推送 private msgSource = new Subject<string>(); msg$ = this.msgSource.asObservable(); // 发送消息的方法 sendMsg(msg: string) { this.msgSource.next(msg); } }
2. msg组件中调用服务发数据
import { Component, OnInit } from '@angular/core'; import { SharedService } from './shared.service'; @Component({ selector: 'app-msg', templateUrl: './msg.component.html' }) export class MsgComponent implements OnInit { msg: string = 'text from msg component'; // 注入服务 constructor(private sharedService: SharedService) {} ngOnInit() { this.sharedService.sendMsg(this.msg); } }
3. filter组件中订阅服务拿数据
import { Component, OnInit } from '@angular/core'; import { SharedService } from './shared.service'; @Component({ selector: 'app-filter', templateUrl: './filter.component.html' }) export class FilterComponent implements OnInit { filterMsg: string = ''; constructor(private sharedService: SharedService) {} ngOnInit() { // 订阅消息,拿到值后赋值给本地属性 this.sharedService.msg$.subscribe(msg => { this.filterMsg = msg; }); } }
内容的提问来源于stack exchange,提问作者user16356529
相关产品推荐
相关产品推荐

