官网
基础指令
*ngFo
(循环)
| <div *ngFor="let item of List"> <h3>{{item.name}}</h3> </div>
|
*ngIf
(如果)
| <div *ngFor="let item of List"> <a [title]="item.name + ' details'"> {{ item.name }} </a> <p *ngIf="item.description"> Description: {{ item.description }} </p> </div>
|
[]
(属性绑定)
| <div *ngFor="let item of List"> <a [title]="item.name + ' details'"> {{ item.name }} </a> </div>
|
style 使用 [ngStyle] = "{color: 'red'}"
绑定
()
(事件绑定)
| <button (click)="share()"> Share </button>
|
[(ngModel | props)]
双向绑定
组件
angular-cli 组件文件结构

angular 的组件都需要使用 angular 提供 component 装饰器生成的
| import { Component, OnInit } from "@angular/core";
@Component({ selector: "app-product-alerts", templateUrl: "./product-alerts.component.html", styleUrls: ["./product-alerts.component.css"], }) export class ProductAlertsComponent implements OnInit {
constructor() {}
ngOnInit() {} }
|
组件注册
| import { NgModule } from '@angular/core'; import { ProductAlertsComponent } from './product-alerts/product-alerts.component';
@NgModule({ declarations: [ ProductListComponent, ],
|
子组件传父组件
用 @input
装饰器 定义一个实例属性,该实例属性可接受父组件传递来的值
| @Component({ selector: "app-product-alerts", templateUrl: "./product-alerts.component.html", styleUrls: ["./product-alerts.component.css"], }) export class ProductAlertsComponent implements OnInit { @Input() product: string;
constructor() {} ngOnInit() {} }
|
子组件 xx.html
| <p *ngIf="product && product.price > 700"> <button>Notify Me</button> </p>
|
注册子组件
| import { NgModule } from '@angular/core'; import { ProductAlertsComponent } from './product-alerts/product-alerts.component';
@NgModule({ declarations: [ ProductListComponent, ],
|
父组件中调用 子组件 并传值
| <app-product-alerts [product]="product"> </app-product-alerts>
|
父组件传子组件
用@output
装饰器声明 值为 new EventEmitter()
的实例属性
| import { Component, Output, EventEmitter } from "@angular/core"; export class ProductAlertsComponent { @Input() product: Product | undefined; @Output() notify = new EventEmitter(); }
|
在需要向父组件通信的节点,调用 notify.emit()
| // 子组件 xx.html <p *ngIf="product && product.price > 700"> <button (click)="notify.emit()">Notify Me</button> </p>
|
父组件 再通过 notify
即可监听到 子组件的 emit
操作
| <app-product-alerts [product]="product" (notify)="onNotify()"> </app-product-alerts>
|