文章目录
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>