ng new my-project => 项目名
ng serve 开启服务,之后可以http://localhost:4200 访问
[attribute] 为属性绑定
(click) 为事件绑定
父子组件通信:
和vue一样,都是用发射机制
子组件中定义输入和输出
@Input attr
@Output nofity
@Output show
定义product-alert作为子组件:
product-alert.component.html:
<div *ngIf="product.price > 700">
<button (click)="onNotifyByMe()">Notify by children</button>
<div>
<!-- 当这两个按键被点击触发,则往外部放射对应的事件 -->
<button (click)="notify.emit()">Notify by children</button>
<button (click)="show.emit()">Show by children</button>
</div>
</div>
product-alert.component.ts:
import { Component, OnInit } from '@angular/core';
import { Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-product-alert',
templateUrl: './product-alert.component.html',
styleUrls: ['./product-alert.component.css']
})
export class ProductAlertComponent implements OnInit {
// input 的输入绑定,外部传的是[]做属性绑定
@Input() product;
// output 往外放射,触发父组件的事件
@Output() notify = new EventEmitter();
@Output() show = new EventEmitter();
constructor() { }
ngOnInit() {
}
onNotifyByMe() {
window.alert("notify by myself");
}
}
可以看到在ts文件中定义了一个输入 product 和两个输出 notify和show
同时在html中通过两个按键绑定了这两个输出的触发事件,整个流程就好像子组件给父组件打了一个电话,告诉他父组件该干什么了,父组件接收到子组件的通知后,就开始做相对应绑定的事情
父组件中的定义:
product-list.component.html
<h2>Product</h2>
<!-- 动态显示List -->
<div *ngFor="let product of productList; index as productId">
<!-- 可以同时绑定多个输出 -->
<!-- [product] 绑定product到子组件中 -->
<!-- () 接收子组件放射出来的事件 -->
<app-product-alert [product]="product" (notify)="onNotify()" (show)="onShow()">
</app-product-alert>
<br/>
<br/>
</div>
product-list.component.ts
import { products } from '../../../assets/products';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
productList = products;
constructor() { }
ngOnInit() {
}
onNotify() {
window.alert("parent notify");
}
onShow() {
window.alert("parent show");
}
}
可以看到父组件中,用[product]向子组件中传递了product信息,同时用(notify)="onNotify()"和(show)="onShow()"来获取到子组件发射出来的事件,并绑定到自己的事件中去。