【Angular】组件之间通讯 Input & Output

本文介绍Angular框架中如何实现父子组件间的数据传递。包括父组件向子组件传递数据的方法及子组件向父组件反馈数据的方式。文章详细展示了通过属性绑定及事件发射器实现通信的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Input  【 父组件向子组件传入数据 

父组件:

1.  准备数据(或引入服务中获取数据)

import { Hero } from '../hero';                                   // 定义类型

import { HEROES } from '../mock-hero';                    // json数据

heroes = HEROES;

2. 公共接口(属性绑定)

<app-hero-detail [hero]="selectedHero"></app-hero-detail>

子组件:

1. 引入input获取数据

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

@Input() hero: Hero;

2. 展示数据

<label>
        name: <input [(ngModel)]="hero.name">

</label>

注:使用双向绑定[( ngModel )],必须引入form模块

import { FormsModule } from '@angular/forms';

imports: [
    FormsModule
  ],

Output  【 子组件向父组件传出数据 

父组件:

1. 公共接口

<app-child  (outer)="receive($event)"></app-child>

2. 方法

    receive(msg: string){
        this.msgFromChild = msg;
    }

子组件:

1. 引入output

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

2.输出output

@Output() private outer = new EventEmitter<string>();

3. 触发事件

<button (click)="sendToParent()">发送给父组件</button>

  sendToParent(){
    this.outer.emit("message from child") ;
  }








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值