Angular 乱炖-1

本文最后更新于:2025年11月18日 下午

Essentials

用组件搭建应用

和 vue 框架一样,angular 也通过组件来构建应用,并且同样的,一个组件也包括了 htmlcssts
如果你熟悉 vue(其实我觉得不熟悉也能直接理解),直接阅读下面这段代码即可快速上手:

1
2
3
4
5
6
7
8
9
10
11
// user-profile.ts
import {ProfilePhoto} from 'profile-photo.ts';
@Component({
selector: 'user-profile',
imports: [ProfilePhoto],
templateUrl: 'user-profile.html',
styleUrl: 'user-profile.css',
})
export class UserProfile {
// Component behavior is defined in here
}

上面这段代码中,创建了 user-profile 这个组件,并导入了 profile-photo 组件,这样在 html 中我们就能通过 <profile-photo /> 来使用这个组件了。

使用 Signals 进行响应式编程

就是 vue 的 refreactive,然后还有跟 vue 一模一样的 computed

1
2
3
4
5
6
7
8
9
10
11
@Component({/* ... */})
export class UserProfile {
firstName = signal('Morgan');
firstNameCapitalized = computed(() => this.firstName().toUpperCase());
modifyNameBySet() {
this.firstName.set('Jaime');
}
modifyNameByUpdate() {
this.firstName.update(name => name.toUpperCase());
}
}

那么,既然 setupdate 都可以用来改变值,那它们的区别在哪里呢?可以简单地理解为:set 是为了设置新值,而 update 是为了在旧值上进行更新。

使用模板编写动态界面

显示动态文本

就是 vue 的双向绑定,定义一个 signal 对象后,在 html 中使用 Mustache 语法将其显示出来:<h1>Profile for {{userName()}}</h1>,然后这个 signal 对象的值如果被更新前端界面的显示也会变。

设置动态属性(Property)和属性(Attribute)

就是 vue 的 v-bind,但是在 angular 里是用方括号:<button [disabled]="isValidUserId()">Save changes</button>

处理用户互动

就是 vue 的 v-on,但是在 angular 里是用圆括号:<button (click)="cancelSubscription($event)">Cancel subscription</button>
此处的 $event 是 angular 的内置变量

使用 @if@for 进行控制流

就是 vue 的 v-ifv-for

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// @if
@if (isAdmin()) {
<h2>Admin settings</h2>
<!-- ... -->
} @else {
<h2>User settings</h2>
<!-- ... -->
}

// @for
<ul class="user-badge-list">
@for (badge of badges(); track badge.id) {
<li class="user-badge">{{badge.name}}</li>
}
</ul>

在这里的 track 可以看成是 vue 的 v-bind:key attribute,用作每一数据项的标识符。

请务必使用 track!它可以显著地提高应用的渲染性能!

使用依赖注入进行模块化设计

老生常谈之什么是依赖注入,引用这个网站上的话来说:“依赖注入其实是将一个模块所依赖的部分作为参数传入,而不是由模块自己去构造。”
个人感觉官网文档的例子给的不是很有参考价值,体现不出依赖注入的作用,这边就不用了,自己来写个一看就懂的:
首先来编写我们的服务类 CalculatorService,作用是提供一个 add 方法来计算传入的 xy 的值,并将结果记录到 results 中(划重点),另外提供了一个 getLastResult 方法来返回最近一次的计算结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// calculator.service.ts
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class CalculatorService {
private results: number[] = [];

add(x: number, y: number): number {
const result = x + y;
this.results.push(result);
return result;
}

getLastResult(): number | undefined {
return this.results.at(-1);
}
}

然后编写两个组件类,一个用于计算,一个用于获取结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// button-add-component.ts
import { Component, inject } from '@angular/core';
import { CalculatorService } from '../services/calculator.service';

@Component({
selector: 'app-button-add',
template: `
<input #a type="number" placeholder="第一个数字" />
<input #b type="number" placeholder="第二个数字" />
<button (click)="add(a.value, b.value)">Add</button>
`,
styles: [``],
})
export class ButtonAddComponent {
private calculator = inject(CalculatorService);
add(a: string, b: string) {
const n1 = Number(a);
const n2 = Number(b);
const result = this.calculator.add(n1, n2);
console.log('Result:', result);
return result;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// button-get-component.ts
import { Component, inject } from '@angular/core';
import { CalculatorService } from '../services/calculator.service';

@Component({
selector: 'app-button-get',
template: `
<span>Last result: {{ lastResult !== null && lastResult !== undefined ? lastResult : 'No result yet' }}</span>
<button (click)="getLastResult()">Get Last Result</button>
`,
styles: [``],
})
export class ButtonGetComponent {
private calculator = inject(CalculatorService);
lastResult: number | null = null;

getLastResult() {
this.lastResult = this.calculator.getLastResult() ?? null;
console.log('Last result:', this.lastResult);
return this.lastResult;
}
}

当我们输入两个数字并按下计算后,再按下取得结果的按钮,就能获取我们上次计算的结果了,这也说明在两个组件中,共享了同一个 CalculatorService 单例。
这是我自己理解的依赖注入在状态持久化上的一个应用,而在这个例子中,也能很好地说明最开始引用的那句话。


这里有一只爱丽丝

希望本文章能够帮到您~


Angular 乱炖-1
https://map1e-g.github.io/2025/11/18/angular-learning-1/
作者
MaP1e-G
发布于
2025年11月18日
许可协议