angular组件传值

小总结:无论是父传子的@Input 装饰器,还是子传父@Output装饰器,都定义在子组件实例中。

父传子@Input
先贴个官网的图片:
在这里插入图片描述

子组件实例

import { Component, Input } from '@angular/core'; // First, import Input
export class ChildItemComponent {
  @Input() item: string; // decorate the property with @Input()
}

子组件模板

<div>{{item}}</div>

父组件模板

<child-item [item]="currentItem"></child-item>

父组件实例

export class AppComponent {
  currentItem = 'aaa';
}

这样,子组件就拿到了父组件中的currentItem值,@Input属性的变化可以用生命周期钩子OnChanges监听。

子传父@output
子组件模板

<input #newItem></input>
<button (click)='addNewItem(newItem.value)'>添加</button>

子组件实例

export class ChildItemComponent {
  @Output() newItemEvent = new EventEmitter<string>();
  addNewItem(value: string){
      this.newItemEvent.emit(value)
  }
}

父组件模板

<child-item (newItemEvent)="addItem($event)"></child-item>

父组件实例

export class AppComponent {
  list=['item1','item2','item3'] 
  addItem(evt:string){
      this.list.push(evt)
  }
}



同时使用 @Input() 和 @Output()

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值