如何在Angular两个子组件间使用@Input与@Output实现数据交互
用@Input和@Output实现Angular子组件间数据传递
核心思路
子组件无法直接互相通信,需以父组件作为数据中转层实现:
- 父组件维护核心数据源
childArray和child2Array - 通过
@Input将数据分别传递给Child1、Child2组件用于渲染 - 子组件通过
@Output触发自定义事件,把待移动的元素通知给父组件 - 父组件处理事件更新数据源后,再通过
@Input同步给两个子组件
1. 父组件(AppComponent)
HTML模板 (app.component.html)
<app-child1 [items]="childArray" (moveToChild2)="handleMoveToChild2($event)" ></app-child1> <app-child2 [items]="child2Array" (moveToChild1)="handleMoveToChild1($event)" ></app-child2>
TypeScript代码 (app.component.ts)
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { childArray = [1, 2, 3, 4, 5]; child2Array = ['a', 'b', 'c', 'd', 'e']; handleMoveToChild2(item: any) { this.child2Array.push(item); this.childArray = this.childArray.filter(el => el !== item); } handleMoveToChild1(item: any) { this.childArray.push(item); this.child2Array = this.child2Array.filter(el => el !== item); } }
2. Child1组件
HTML模板 (child1.component.html)
<div class="parentDiv"> <div class="parentBox1" *ngFor="let item of items" (click)="onMoveToChild2(item)" > {{ item }} </div> </div>
TypeScript代码 (child1.component.ts)
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child1', templateUrl: './child1.component.html', styleUrls: ['./child1.component.css'] }) export class Child1Component { @Input() items!: any[]; @Output() moveToChild2 = new EventEmitter<any>(); onMoveToChild2(item: any) { this.moveToChild2.emit(item); } }
CSS样式 (child1.component.css)
.parentDiv { width: 100px; height: 500px; background-color: brown; float: left; margin: 30px; } .parentBox1 { width: 20px; height: 20px; background-color: blueviolet; margin: 15px; padding: 15px; float: left; }
3. Child2组件
HTML模板 (child2.component.html)
<div class="parent2Div"> <div class="parentBox2" *ngFor="let item of items" (click)="onMoveToChild1(item)" > {{ item }} </div> </div>
TypeScript代码 (child2.component.ts)
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child2', templateUrl: './child2.component.html', styleUrls: ['./child2.component.css'] }) export class Child2Component { @Input() items!: any[]; @Output() moveToChild1 = new EventEmitter<any>(); onMoveToChild1(item: any) { this.moveToChild1.emit(item); } }
CSS样式 (child2.component.css)
.parent2Div{ width: 100px; height: 500px; background-color: blue; float:left; margin: 30px; } .parentBox2{ width: 20px; height: 20px; background-color: green; margin: 15px; padding: 15px; float: left; }
关键说明
@Input():接收父组件传递的渲染数据,是子组件获取外部数据的入口@Output()+EventEmitter:子组件向父组件传递事件的方式,仅负责触发通知,不处理数据逻辑- 所有数据更新逻辑集中在父组件,保证数据源唯一,避免子组件间状态不一致问题
内容的提问来源于stack exchange,提问作者Nancy
相关产品推荐
相关产品推荐

