Angular 使用教程——基本语法和双向数据绑定

news/2025/2/12 8:49:41/

Angular 是一个应用设计框架与开发平台,旨在创建高效而精致的单页面应用

Angular 是一个基于 TypeScript 构建的开发平台。它包括:一个基于组件的框架,用于构建可伸缩的 Web 应用,一组完美集成的库,涵盖各种功能,包括路由、表单管理、客户端-服务器通信等,一套开发工具,可帮助你开发、构建、测试和更新代码。借助 Angular,无论单人项目还是企业级应用,你都能获得平台带来的优势。Angular 的设计目标之一就是让更新更容易,因此你可以用最小的成本升级到最新的 Angular 版本

Angular诞生历史,AngularJS诞生于2009年,由Misko Hevery 等人创建,是一款构建用户界面的前端框架,后为Google收购。AngularJS是一个应用设计框架与开发平台,用于创建高效、复杂、精致的单页面应用,通过新的属性和表达式扩展了 HTML,实现一套框架,多种平台,移动端和桌面端。AngularJS有着诸多特性,最为核心的是:MVVM、模块化、自动化双向数据绑定、语义化标签、依赖注入等等。Angular是AngularJS的重写,Angular2以后官方命名为Angular,2.0以前版本称为AngularJS。AngularJS是用JavaScript编写,而Angular采用TypeScript语言编写,是ECMAScript 6的超集

Angular官网:https://angular.cn/

目录

1、创建 Angular 项目

2、点击事件

3、if 语句

3.1、if 形式

3.2、if else 形式

3.3、angular 17 @if 形式

4、for 语句

4.1、*ngFor 形式

4.2、angular 17 @for 形式

5、switch 语句

5.1、ngSwitch 形式

5.2、angular 17 @switch 形式

6、双向数据绑定


1、创建 Angular 项目

Angular 和 Node 版本关系

Angular 需要 Node.js 的活跃 LTS 版或维护期 LTS 版

笔者使用的 node 版本是 20.9.0

安装 Angular CLI 

如果已经安装过Angular CLI ,可以跳过

npm install -g @angular/cli

创建项目

在新的文件目录下执行下面创建项目命令

ng new angular-learn

笔者新建的项目名为 angular-learn

创建完成

使用 vs code 打开项目代码

笔者创建的 Angular 版本是17

项目结构

运行项目

npm run start

浏览器访问:http://localhost:4200

项目创建成功

2、点击事件

先将 app.component.html 文件内容清空,只保留<router-outlet></router-outlet>

在 app.component.html 中添加button标签,并按下面代码添加点击事件

<button (click)="add()">添加</button>
<router-outlet></router-outlet>

然后在 app.component.ts 文件中写add 事件内容

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';@Component({selector: 'app-root',standalone: true,imports: [CommonModule, RouterOutlet],templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {title = 'angular-learn';add() {alert('晓看天色暮看云,行也思君,坐也思君')}
}

运行效果

获取事件本身

app.component.html 


<button (click)="add()">添加</button>
<button (click)="add2($event)">添加2</button>
<router-outlet></router-outlet>

app.component.ts 

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';@Component({selector: 'app-root',standalone: true,imports: [CommonModule, RouterOutlet],templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {title = 'angular-learn';add() {alert('晓看天色暮看云,行也思君,坐也思君')}add2(e:MouseEvent) {console.log(e);}
}

运行效果

3、if 语句

3.1、if 形式

在 app.component.ts 中定义变量 isPoetry

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';@Component({selector: 'app-root',standalone: true,imports: [CommonModule, RouterOutlet],templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {title = 'angular-learn';add() {alert('晓看天色暮看云,行也思君,坐也思君')}add2(e:MouseEvent) {console.log(e);}isPoetry:boolean = true
}

app.component.html 中写 if 判断


<button (click)="add()">添加</button>
<button (click)="add2($event)">添加2</button><p *ngIf="isPoetry">山有木兮木有枝,心悦君兮君不知
</p><router-outlet></router-outlet>

运行效果

3.2、if else 形式

app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';@Component({selector: 'app-root',standalone: true,imports: [CommonModule, RouterOutlet],templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {title = 'angular-learn';add() {alert('晓看天色暮看云,行也思君,坐也思君')}add2(e:MouseEvent) {console.log(e);}isPoetry:boolean = trueisPoetry2:boolean = truechangePoetry() {this.isPoetry2 = false}
}

app.component.html


<button (click)="add()">添加</button>
<button (click)="add2($event)">添加2</button><p *ngIf="isPoetry">山有木兮木有枝,心悦君兮君不知
</p>
<button (click)="changePoetry()">修改isPoetry2</button>
<ng-container *ngIf="isPoetry2; else elseTemplate"><p>与君初相识,犹如故人归</p>
</ng-container>
<ng-template #elseTemplate><p>愿我如星君如月,夜夜流光相皎洁</p>
</ng-template><router-outlet></router-outlet>

运行效果

3.3、angular 17 @if 形式


<button (click)="add()">添加</button>
<button (click)="add2($event)">添加2</button><p *ngIf="isPoetry">山有木兮木有枝,心悦君兮君不知
</p>
<button (click)="changePoetry()">修改isPoetry2</button>
<ng-container *ngIf="isPoetry2; else elseTemplate"><p>与君初相识,犹如故人归</p>
</ng-container>
<ng-template #elseTemplate><p>愿我如星君如月,夜夜流光相皎洁</p>
</ng-template><!-- angular17 写法 -->
@if (isPoetry2) {<p>似此星辰非昨夜,为谁风露立中宵</p>
}
@else {<p>曾经沧海难为水,除却巫山不是云</p>
}<router-outlet></router-outlet>

运行效果

4、for 语句

4.1、*ngFor 形式

app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';@Component({selector: 'app-root',standalone: true,imports: [CommonModule, RouterOutlet],templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {title = 'angular-learn';add() {alert('晓看天色暮看云,行也思君,坐也思君')}add2(e:MouseEvent) {console.log(e);}isPoetry:boolean = trueisPoetry2:boolean = truechangePoetry() {this.isPoetry2 = false}// 定义数组poetrys:Array<string> = ['死生契阔,与子成说','执子之手,与子偕老','我心匪石,不可转也','有一美人兮,见之不忘']
}

app.component.html


<button (click)="add()">添加</button>
<button (click)="add2($event)">添加2</button><p *ngIf="isPoetry">山有木兮木有枝,心悦君兮君不知
</p>
<button (click)="changePoetry()">修改isPoetry2</button>
<ng-container *ngIf="isPoetry2; else elseTemplate"><p>与君初相识,犹如故人归</p>
</ng-container>
<ng-template #elseTemplate><p>愿我如星君如月,夜夜流光相皎洁</p>
</ng-template><!-- angular17 写法 -->
@if (isPoetry2) {<p>似此星辰非昨夜,为谁风露立中宵</p>
}
@else {<p>曾经沧海难为水,除却巫山不是云</p>
}<!-- for 语句 -->
<p *ngFor="let poetry of poetrys let i = index">{{i+1}}、{{poetry}}
</p>
<router-outlet></router-outlet>

运行效果

4.2、angular 17 @for 形式


<button (click)="add()">添加</button>
<button (click)="add2($event)">添加2</button><p *ngIf="isPoetry">山有木兮木有枝,心悦君兮君不知
</p>
<button (click)="changePoetry()">修改isPoetry2</button>
<ng-container *ngIf="isPoetry2; else elseTemplate"><p>与君初相识,犹如故人归</p>
</ng-container>
<ng-template #elseTemplate><p>愿我如星君如月,夜夜流光相皎洁</p>
</ng-template><!-- angular17 写法 -->
@if (isPoetry2) {<p>似此星辰非昨夜,为谁风露立中宵</p>
}
@else {<p>曾经沧海难为水,除却巫山不是云</p>
}<!-- for 语句 -->
<p *ngFor="let poetry of poetrys let i = index">{{i+1}}、{{poetry}}
</p><!-- angular 17 @for 语句 -->
@for (item of poetrys; track item) {<div>{{item}}</div>
} @empty {Empty list of poetrys
}@for (item of poetrys; track $index) {<p>{{$index+1}}、{{item}}</p>
}
<router-outlet></router-outlet>

5、switch 语句

5.1、ngSwitch 形式

app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';@Component({selector: 'app-root',standalone: true,imports: [CommonModule, RouterOutlet],templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {title = 'angular-learn';add() {alert('晓看天色暮看云,行也思君,坐也思君')}add2(e:MouseEvent) {console.log(e);}isPoetry:boolean = trueisPoetry2:boolean = truechangePoetry() {this.isPoetry2 = false}// 定义数组poetrys:Array<string> = ['死生契阔,与子成说','执子之手,与子偕老','我心匪石,不可转也','有一美人兮,见之不忘']author:number = 2changAuthor() {this.author = 3}
}

app.component.html


<button (click)="add()">添加</button>
<button (click)="add2($event)">添加2</button><p *ngIf="isPoetry">山有木兮木有枝,心悦君兮君不知
</p>
<button (click)="changePoetry()">修改isPoetry2</button>
<ng-container *ngIf="isPoetry2; else elseTemplate"><p>与君初相识,犹如故人归</p>
</ng-container>
<ng-template #elseTemplate><p>愿我如星君如月,夜夜流光相皎洁</p>
</ng-template><!-- angular17 写法 -->
@if (isPoetry2) {<p>似此星辰非昨夜,为谁风露立中宵</p>
}
@else {<p>曾经沧海难为水,除却巫山不是云</p>
}<!-- for 语句 -->
<p *ngFor="let poetry of poetrys let i = index">{{i+1}}、{{poetry}}
</p><!-- angular 17 @for 语句 -->
@for (item of poetrys; track item) {<div>{{item}}</div>
} @empty {Empty list of poetrys
}@for (item of poetrys; track $index) {<p>{{$index+1}}、{{item}}</p>
}<button (click)="changAuthor()">修改作者</button>
<!-- angular switch语法 -->
<div [ngSwitch]="author"><p *ngSwitchCase="1">青天有月来几时 我今停杯一问之</p><p *ngSwitchCase="2">明月几时有,把酒问青天</p><p *ngSwitchDefault>江畔何人初见月,江月何年初照人</p>
</div>
<router-outlet></router-outlet>

运行效果

5.2、angular 17 @switch 形式

app.component.html


<button (click)="add()">添加</button>
<button (click)="add2($event)">添加2</button><p *ngIf="isPoetry">山有木兮木有枝,心悦君兮君不知
</p>
<button (click)="changePoetry()">修改isPoetry2</button>
<ng-container *ngIf="isPoetry2; else elseTemplate"><p>与君初相识,犹如故人归</p>
</ng-container>
<ng-template #elseTemplate><p>愿我如星君如月,夜夜流光相皎洁</p>
</ng-template><!-- angular17 写法 -->
@if (isPoetry2) {<p>似此星辰非昨夜,为谁风露立中宵</p>
}
@else {<p>曾经沧海难为水,除却巫山不是云</p>
}<!-- for 语句 -->
<p *ngFor="let poetry of poetrys let i = index">{{i+1}}、{{poetry}}
</p><!-- angular 17 @for 语句 -->
@for (item of poetrys; track item) {<div>{{item}}</div>
} @empty {Empty list of poetrys
}@for (item of poetrys; track $index) {<p>{{$index+1}}、{{item}}</p>
}<button (click)="changAuthor()">修改作者</button>
<!-- angular switch语法 -->
<div [ngSwitch]="author"><p *ngSwitchCase="1">青天有月来几时 我今停杯一问之</p><p *ngSwitchCase="2">明月几时有,把酒问青天</p><p *ngSwitchDefault>江畔何人初见月,江月何年初照人</p>
</div><!-- angular17 switch -->
@switch (author) {@case (1) {<p>若非群玉山头见 会向瑶台月下逢</p>}@case (2) {<p>春宵一刻值千值千金,花有清香月有阴</p>}@default {<p>情催桃李艳,心寄管弦飞</p>}
}
<router-outlet></router-outlet>

运行效果

6、双向数据绑定

想要实现双向数据绑定,需要引入angular 内置的 FormsModule 模块

在 app.component.ts 文件中引入

import { FormsModule } from '@angular/forms';

并在 @Component 的 import 中添加 FormsModule

app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { FormsModule } from '@angular/forms';@Component({selector: 'app-root',standalone: true,imports: [CommonModule, RouterOutlet, FormsModule],templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {title = 'angular-learn';add() {alert('晓看天色暮看云,行也思君,坐也思君')}add2(e:MouseEvent) {console.log(e);}isPoetry:boolean = trueisPoetry2:boolean = truechangePoetry() {this.isPoetry2 = false}// 定义数组poetrys:Array<string> = ['死生契阔,与子成说','执子之手,与子偕老','我心匪石,不可转也','有一美人兮,见之不忘']author:number = 2changAuthor() {this.author = 3}poetryContent:string = '彼采葛兮,一日不见,如三月兮'}

app.component.html


<button (click)="add()">添加</button>
<button (click)="add2($event)">添加2</button><p *ngIf="isPoetry">山有木兮木有枝,心悦君兮君不知
</p>
<button (click)="changePoetry()">修改isPoetry2</button>
<ng-container *ngIf="isPoetry2; else elseTemplate"><p>与君初相识,犹如故人归</p>
</ng-container>
<ng-template #elseTemplate><p>愿我如星君如月,夜夜流光相皎洁</p>
</ng-template><!-- angular17 写法 -->
@if (isPoetry2) {<p>似此星辰非昨夜,为谁风露立中宵</p>
}
@else {<p>曾经沧海难为水,除却巫山不是云</p>
}<!-- for 语句 -->
<!-- <p *ngFor="let poetry of poetrys let i = index">{{i+1}}、{{poetry}}
</p> --><!-- angular 17 @for 语句 -->
<!-- @for (item of poetrys; track item) {<div>{{item}}</div>
} @empty {Empty list of poetrys
}@for (item of poetrys; track $index) {<p>{{$index+1}}、{{item}}</p>
} --><button (click)="changAuthor()">修改作者</button>
<!-- angular switch语法 -->
<div [ngSwitch]="author"><p *ngSwitchCase="1">青天有月来几时 我今停杯一问之</p><p *ngSwitchCase="2">明月几时有,把酒问青天</p><p *ngSwitchDefault>江畔何人初见月,江月何年初照人</p>
</div><!-- angular17 switch -->
@switch (author) {@case (1) {<p>若非群玉山头见 会向瑶台月下逢</p>}@case (2) {<p>春宵一刻值千值千金,花有清香月有阴</p>}@default {<p>情催桃李艳,心寄管弦飞</p>}
}<input [(ngModel)]="poetryContent" type="text" style="width: 200px;">
{{poetryContent}}
<router-outlet></router-outlet>

运行效果

​​​​​​​

至此完


http://www.ppmy.cn/news/1212669.html

相关文章

LeetCode110. Balanced Binary Tree

文章目录 一、题目二、题解 一、题目 Given a binary tree, determine if it is height-balanced . Example 1: Input: root [3,9,20,null,null,15,7] Output: true Example 2: Input: root [1,2,2,3,3,null,null,4,4] Output: false Example 3: Input: root [] Output…

AI:80-基于深度学习的医学图像分割与病变识别

🚀 本文选自专栏:人工智能领域200例教程专栏 从基础到实践,深入学习。无论你是初学者还是经验丰富的老手,对于本专栏案例和项目实践都有参考学习意义。 ✨✨✨ 每一个案例都附带有在本地跑过的代码,详细讲解供大家学习,希望可以帮到大家。欢迎订阅支持,正在不断更新中,…

代码随想录算法训练营第四十九天|121. 买卖股票的最佳时机、122. 买卖股票的最佳时机 II

第九章 动态规划part10 121. 买卖股票的最佳时机 给定一个数组 prices &#xff0c;它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票&#xff0c;并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最…

数据可视化PCA与t-SNE

PCA&#xff08;主成分分析&#xff09;和t-SNE&#xff08;t分布随机近邻嵌入&#xff09;都是降维技术&#xff0c;可以用于数据的可视化和特征提取。 降维&#xff1a;把数据或特征的维数降低&#xff0c;其基本作用包括&#xff1a; 提高样本密度&#xff0c;以及使基于欧…

链表的逆置

方法1&#xff1a; 依次将指针反向&#xff0c;最后令头指针指向尾元素。 逆置过程如下&#xff1a; 当q指针为空时&#xff0c;循环结束。 //试写一算法&#xff0c;对单链表实现就地逆置&#xff0c; void Reverse1(List plist)//太复杂,不用掌握 {assert(plist ! NULL);i…

MySQL:日志系统

目录 概述错误日志&#xff08;error log&#xff09;慢查询日志&#xff08;slow query log&#xff09;一般查询日志( general log )中继日志&#xff08;relay log&#xff09;Buffer Pool 缓存回滚日志&#xff08;undo log)概述undo log 作用undo log 的存储机制Undo log …

第七章、python的变量、函数及其应用(7.3-7.6)------匿名函数lambda、嵌套函数、闭包、装饰器

目录 7.3 匿名函数lambda 7.4 嵌套函数(Nested Function) 7.5 闭包(Closure) 7.6 装饰器 7.3 匿名函数lambda 关键字lambda可以定义一个匿名函数,匿名函数是关键字def定义的标准函数的简化形式,匿名函数只适合比较简单的函数,对于太复杂的函数只适合def来定义。匿名函数的用…

linux之IPC

linux之IPC 什么是IPC共享内存(shm)ftokshmgetshmatshmdtshmctl 消息队列msggetmsgrcvmsgsndmsgctl 旗语(信号量)semgetsemctlsemopsem三级标题三级标题 ipc命令守护进程查看守护进程 什么是IPC IPC: Inter(内核) Process(进程) Communicton&#xff08;通信&#xff09; 共享内…