Angular4学习笔记(六)- Input和Output

概述

Angular中的输入输出是通过注解@Input@Output来标识,它位于组件控制器的属性上方。
输入输出针对的对象是父子组件。

演示

Input

  • 新建项目connInComponents:ng new connInComponents.
  • 新增组件stock:ng g component stock.
  • stock.component.ts中新增属性stockName并将其标记为输入@Input():
  @Input()
  protected stockName: string;
  • 既然有@Input()则应有对应的父组件,此处使用默认生成的主组件app.
    在父组件中定义属性keyWork并通过视图文件app.component.html中的标签<input>来进行双向绑定,最后,在视图文件app.component.html中嵌入子组件并进行赋值:
//ts
protected keyWord: string;

//html
<input placeholder="请输入股票名称" [(ngModel)]="keyWord">
<app-stock [stockName]="keyWord"></app-stock>

注意,[(ngModel)]需要在app.module.ts中引入模块FormsModule
这样就完成了父组件向子组件赋值的操作了。

  • 在子组件中进行展示
<p>
  stock works!
</p>
<div>
  股票名称:{{stockName}}
</div>

Output

Output的赋值操作不像Input那样简单,它需要通过位于@angular/core包下的EventEmitter对象来监听并处理数据。并且需要传入泛型类来规定参数类型。

需求

在父子组件中各自定义一个表示股票价格的属性,并通过Output将子组件中的价格信息传给父组件。

  • 由于EventEmitter需要传入泛型类,因此我们首先定义一个股票信息类:
export class StockInfo {
  constructor(public name: string, public price: number) {
    this.name = name;
    this.price = price;
  }
}
  • 在子组件stock.component.ts中新增属性stockPriceevent,并在初始化方法中为stockPrice赋值并通过event将当前绑定对象发射出去:
  protected stockPrice: number;
  @Output()
  protected event: EventEmitter<StockInfo> = new EventEmitter();

  ngOnInit() {
    setInterval(() => {
      const stock: StockInfo = new StockInfo(this.stockName, 100 * Math.random());
      this.stockPrice = stock.price;
      this.event.emit(stock);
    }, 3000);
  }

此时子组件的发射动作已完成,那么如何接收发射的数据呢?

  • 在父组件中定义价格属性currentPrice和接收方法eventHandler
  protected currentPrice: number;

  eventHandler(stock: StockInfo) {
    this.currentPrice = stock.price;
  }
  • 在嵌入的子组件视图元素<app-stock>上添加绑定关系:
<app-stock [stockName]="keyWord" (event)="eventHandler($event)"></app-stock>

其中event对应子组件属性,eventHandler对应父组件接收并处理子组件传来的方法,$event代表泛型类参数,此处是一个类型为StockInfo的实例。

此时赋值操作已经完成,在父子组件的视图文件中添加显示接收到的信息(股票价格)即可:
stock.component.html

<div>
  股票名称:{{stockName}}<br>当前价格:{{stockPrice | number:'2.1-2'}}
</div>

app.component.html

<div>
  股票名称:{{keyWord}}<br>当前价格:{{currentPrice | number:'2.1-2'}}
</div>

tips

@Output可以传递参数,其值与嵌入的子组件视图元素<app-stock>上绑定的数据名称统一。
@Output('lastPrice'),那么

<app-stock [stockName]="keyWord" (event)="eventHandler($event)"></app-stock>

相应改为:

<app-stock [stockName]="keyWord" (lastPrice)="eventHandler($event)"></app-stock>

效果

Demo

下载

posted @   舒山  阅读(7797)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2016-11-01 解决error: Your local changes to the following files would be overwritten by merge
2016-11-01 Spring-JDBC配置
2016-11-01 server library[unbound] 服务未绑定解决办法
点击右上角即可分享
微信分享提示