父传子
子组件
import { Component, OnInit } from '@angular/core';
import { Input } from '@angular/core';
export class ProductAlertsComponent implements OnInit {
@Input() product;
constructor() { }
ngOnInit() {
}
}
父组件
<button (click)="share()">
Share
</button>
<app-product-alerts
[product]="product">
</app-product-alerts>
子传父
子组件
import { Component } from '@angular/core';
import { Input } from '@angular/core';
import { Output, EventEmitter } from '@angular/core';
export class ProductAlertsComponent {
@Input() product;
@Output() notify = new EventEmitter();
}
<p *ngIf="product.price > 700">
<button (click)="notify.emit()">Notify Me</button>
</p>
父组件
export class ProductListComponent {
products = products;
share() {
window.alert('The product has been shared!');
}
onNotify() {
window.alert('You will be notified when the product goes on sale');
}
}
<button (click)="share()">
Share
</button>
<app-product-alerts
[product]="product"
(notify)="onNotify()">
</app-product-alerts>