Angular 初探

官网

基础指令

*ngFo(循环)

1
2
3
<div *ngFor="let item of List">
<h3>{{item.name}}</h3>
</div>

*ngIf (如果)

1
2
3
4
5
6
7
8
<div *ngFor="let item of List">
<a [title]="item.name + ' details'">
{{ item.name }}
</a>
<p *ngIf="item.description">
Description: {{ item.description }}
</p>
</div>

[](属性绑定)

1
2
3
4
5
<div *ngFor="let item of List">
<a [title]="item.name + ' details'">
{{ item.name }}
</a>
</div>

style 使用 [ngStyle] = "{color: 'red'}" 绑定

()(事件绑定)

1
2
3
<button (click)="share()">
Share
</button>

[(ngModel | props)] 双向绑定

组件

angular-cli 组件文件结构

angular 的组件都需要使用 angular 提供 component 装饰器生成的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 {
// implements 类似 extends 但一般用于 interface, 且内置方便必须重写

constructor() {}

// 重写 OnInit 的内置方法
ngOnInit() {}
}

组件注册

1
2
3
4
5
6
7
8
// xx.module.ts
import { NgModule } from '@angular/core';
import { ProductAlertsComponent } from './product-alerts/product-alerts.component';

@NgModule({
declarations: [
ProductListComponent,
],

子组件传父组件

@input装饰器 定义一个实例属性,该实例属性可接受父组件传递来的值

1
2
3
4
5
6
7
8
9
10
11
12
// 子组件 xx.ts
@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

1
2
3
<p *ngIf="product && product.price > 700">
<button>Notify Me</button>
</p>

注册子组件

1
2
3
4
5
6
7
import { NgModule } from '@angular/core';
import { ProductAlertsComponent } from './product-alerts/product-alerts.component';

@NgModule({
declarations: [
ProductListComponent,
],

父组件中调用 子组件 并传值

1
2
<app-product-alerts [product]="product">
</app-product-alerts>

父组件传子组件

@output装饰器声明 值为 new EventEmitter()的实例属性

1
2
3
4
5
6
// 子组件 xx.ts
import { Component, Output, EventEmitter } from "@angular/core";
export class ProductAlertsComponent {
@Input() product: Product | undefined;
@Output() notify = new EventEmitter();
}

在需要向父组件通信的节点,调用 notify.emit()

1
2
3
4
// 子组件 xx.html
<p *ngIf="product && product.price > 700">
<button (click)="notify.emit()">Notify Me</button>
</p>

父组件 再通过 notify 即可监听到 子组件的 emit 操作

1
2
<app-product-alerts [product]="product" (notify)="onNotify()">
</app-product-alerts>

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!