Angular子父组件传参

Angular子组件传参

版本:Angular v15
子组件中:从core导入Input

// 子组件
import { Component , Input} from '@angular/core';

export class ProductAlertsComponent {
  @Input() product!:Product; // 接收传过来的参数
}

父组件通过 [product]=“item” 传参

<div *ngFor="let item of products; >
  <app-product-alerts [product]="item"></app-product-alerts>
</div>

子组件通知父组件

子组件 notify.emit() 派发事件

// child.component.ts
import { Component , Input, Output, EventEmitter} from '@angular/core';
import { Product } from '../products';

export class ProductAlertsComponent {
  @Input() product!:Product;
  @Output() notify = new EventEmitter(); // 通过 notify.emit() 通知父组件

  constructor() { }
}

// child.component.html
<button (click)="notify.emit()">通知我</button>

父组件 (notify)=“onNotify” 绑定事件

export class ProductListComponent {
  // 父级接收子组件事件
  onNotify() {
    window.alert('You will be notified when the product goes on sale');
  }
}

// 父组件 html (notify)="onNotify" 绑定事件
<div *ngFor="let item of products; let i = index; let odd = odd" [class.odd]="odd">
  <app-product-alerts [product]="item" (notify)="onNotify()"></app-product-alerts>
</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值