Skip to content

3. 组件

3.1. 示例 10:组件及其输入

组件是界面中可复用的一部分。本示例显示医生的简介:一个名为[DoctorCard](子组件)的组件,被组件[App](父组件)多次使用。

组件的文件通常存放在以组件命名的文件夹中:

1
2
3
4
5
6
7
8
10-components/src/app/
├── doctor-card/
│   ├── doctor-card.ts     组件的类
│   ├── doctor-card.html   它的模板
│   └── doctor-card.css    它的样式
├── doctor.ts             Doctor 类型
├── app.ts
└── app.html

父组件和子组件共享的数据类型:

1
2
3
4
5
6
7
8
9
// 父组件(App)和子组件(DoctorCard)共享的数据类型
export interface Doctor {
  id: number;
  title: string;
  firstName: string;
  lastName: string;
  specialty: string;
  available: boolean;
}

3.1.1. 子组件

// =========================================================================
// 10-components/src/app/doctor-card/doctor-card.ts - 一个子组件
// -------------------------------------------------------------------------
// 它通过输入从父组件接收数据,输入用
// input() 声明:每个输入都是只读的 signal,它跟随
// 父组件传入的值。其类型在编译时检查:
// <app-doctor-card [doctor]="42"> 会被拒绝。
//
// 黄金法则:组件绝不修改它的输入。数据
// 从父组件流向子组件;若要请求更改,
// 子组件发出一个事件(参见示例 11)。
// =========================================================================

import { booleanAttribute, Component, computed, input } from '@angular/core';
import { Doctor } from '../doctor';

@Component({
  // 选择器:在父组件中表示此组件的标签
  selector: 'app-doctor-card',
  templateUrl: './doctor-card.html',
  styleUrl: './doctor-card.css',
})
export class DoctorCard {
  // input.required:父组件必须提供此输入
  readonly doctor = input.required<Doctor>();
  readonly rank = input.required<number>();
  // input(默认值):可选的输入。booleanAttribute
  // 允许简单地写 <app-doctor-card compact> 表示 true
  readonly compact = input(false, { transform: booleanAttribute });

  // 基于输入的 computed:若父组件修改了输入则重新计算
  protected readonly initials = computed(() => `${this.doctor().firstName[0]}${this.doctor().lastName[0]}`);
}
  • 第 19 行:选择器:父组件将写[<app-doctor-card>];
  • 第 25–29 行:组件的输入([inputs])——由其父组件传递给它的数据。[input()]创建一个只读信号,用于跟踪父组件传入的值:
    • 第 25–26 行:[input.required<T>()]:必需的输入。如果父组件的模板中省略了[[doctor]],将导致编译错误;
    • 第 29 行:[input(default value)]:可选的输入。[transform]选项用于转换接收到的值:[booleanAttribute]将属性的存在([<app-doctor-card compact>],没有值)转换为[true],就像 HTML 属性[disabled]一样;
  • 第 32 行:一个基于输入的 [computed]:如果父组件改变了输入,就会重新计算。

输入不是[protected]的:它们是组件公共接口的一部分,也就是其父组件所使用的接口。

黄金法则:组件绝不修改自己的输入(无论如何它们都是只读的)。数据从父组件流向子组件;若要请求更改,子组件会发出事件(示例 11)。

<div class="card h-100" [class.border-success]="doctor().available">
  <div class="card-body d-flex gap-3 align-items-center">
    <div class="initials">{{ initials() }}</div>
    <div>
      <!-- 输入是 signal:通过调用来读取 -->
      <h2 class="h6 mb-1">{{ rank() }}. {{ doctor().title }} {{ doctor().firstName }} {{ doctor().lastName }}</h2>
      @if (!compact()) {
        <p class="mb-0 text-muted small">{{ doctor().specialty }}</p>
      }
    </div>
  </div>
</div>
  • 第 1、6、8 行:输入是信号:通过调用它们来读取;
  • 第 7–9 行:专业仅在卡片的普通版本中显示。
/* 组件的样式:仅作用于它自己的元素 */
.initials {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #dd0031;
  color: white;
  font-weight: bold;
}

类[initials]仅作用于此组件:另一个组件可以有自己的类[initials],而不会产生任何冲突。

3.1.2. 父组件

// =========================================================================
// 10-components/src/app/app.ts - 父组件
// -------------------------------------------------------------------------
// 它导入 DoctorCard 组件(imports 数组),并将其作为
// 一个新的 HTML 标签 <app-doctor-card> 使用,可按
// 需使用任意多次:组件是界面中可复用的部分,拥有
// 自己的数据、模板和样式。
// =========================================================================

import { Component, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DoctorCard } from './doctor-card/doctor-card';
import { Doctor } from './doctor';

@Component({
  selector: 'app-root',
  imports: [FormsModule, DoctorCard],
  templateUrl: './app.html',
})
export class App {
  protected readonly doctors = signal<Doctor[]>([
    { id: 1, title: 'Mme', firstName: 'Marie', lastName: 'PELISSIER', specialty: 'general practitioner', available: true },
    { id: 2, title: 'Mr', firstName: 'Paul', lastName: 'TATOU', specialty: 'pediatrician', available: false },
    { id: 3, title: 'Melle', firstName: 'Sophie', lastName: 'DUPONT', specialty: 'general practitioner', available: true },
  ]);
  protected readonly compact = signal(false);

  // 父组件修改它的数据:相关的子组件随之更新
  protected toggleAvailability(): void {
    this.doctors.update((list) => list.map((m) => ({ ...m, available: !m.available })));
  }
}
  • 第 17 行:父组件导入子组件;否则,[<app-doctor-card>]将是一个未知标签,编译会失败;
  • 第 29–31 行:父组件修改它自己的数据。它将每位医生替换为一个修改后的副本:传给每张卡片的[m]对象发生变化,卡片随之更新。
<div class="container py-4">
  <h1 class="h3 mb-3">Example 10 - components and their inputs</h1>
  <div class="d-flex gap-3 mb-3">
    <label class="form-check-label">
      <input type="checkbox" class="form-check-input" [(ngModel)]="compact"> compact display
    </label>
    <button class="btn btn-sm btn-outline-primary" (click)="toggleAvailability()">Toggle availability</button>
  </div>
  <div class="row g-3">
    @for (m of doctors(); track m.id; let i = $index) {
      <div class="col-md-4">
        <!-- [doctor]="m" 传递的是对象 m(一个表达式);
             doctor="m"(不带方括号)则会传递字符串 "m" -->
        <app-doctor-card [doctor]="m" [rank]="i + 1" [compact]="compact()" />
      </div>
    }
  </div>
  <p class="mt-3 mb-1 small text-muted">The same card, in compact version, through an attribute without a value:</p>
  <div class="w-50">
    <app-doctor-card [doctor]="doctors()[0]" [rank]="1" compact />
  </div>
</div>
  • 第 14 行:子组件被用作 HTML 标签。[[doctor]="m"]是对输入 [doctor]的属性绑定:它传递的是对象 [m]。如果没有方括号,[doctor="m"]传递的将是字符串 ["m"],编译器会拒绝它。没有内容的组件可以使用自闭合标签来书写([/>]);
  • 第 20 行:[compact],没有值:得益于 [booleanAttribute],输入接收到 [true]。

[npm start 10-components];点击“Toggle availability”:

Image

3.2. 示例 11:组件的输出与 model()

子组件有两种方式将信息发回给父组件:

  1. 发出一个事件(即输出,[output]),父组件像监听 HTML 事件一样监听它;2. 在 [model()] 上建立双向连接,[[( )]]。

3.2.1. 发送事件

一个计数器,每次点击以及达到上限时都会通知其父组件:

// =========================================================================
// 11-outputs-model/src/app/counter/counter.ts
// -------------------------------------------------------------------------
// 通知父组件的子组件:output() 声明组件
// 可以发出的事件,并带有其数据的类型。父组件像监听
// HTML 事件一样监听它:<app-counter (incremented)="..." (limit)="...">。
// =========================================================================

import { Component, input, output, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <div class="d-flex align-items-center gap-2 mb-2">
      <span class="w-25">{{ label() }}</span>
      <button class="btn btn-sm btn-outline-primary" (click)="plus()">+1</button>
      <span class="badge text-bg-secondary">{{ value() }} / {{ max() }}</span>
    </div>
  `,
})
export class Counter {
  readonly label = input.required<string>();
  readonly max = input.required<number>();

  // 两个事件:incremented(带新值)和 limit(无数据)
  readonly incremented = output<number>();
  readonly limit = output<void>();

  protected readonly value = signal(0);

  protected plus(): void {
    if (this.value() >= this.max()) {
      this.limit.emit();
      return;
    }
    this.value.update((v) => v + 1);
    this.incremented.emit(this.value());
  }
}
  • 第 13–19 行:组件的模板,写在装饰器中(属性 [template],用反引号括起来);
  • 第 26–27 行:[output<T>()] 声明一个输出:组件可以发出的事件,以及其数据的类型。[limit] 没有数据([void]);
  • 第 33 行和第 37 行:[emit(data)] 发出事件;父组件接收数据。

避免以浏览器事件命名输出([change]、[click]……):组件内部元素发出的浏览器事件会向上冒泡到其宿主元素,父组件也会接收到它们。

3.2.2. 双向绑定

一个“自定义”表单字段(标签、字段、提示、字符计数器),与父组件的数据(例如 [ngModel])相关联:

// =========================================================================
// 11-outputs-model/src/app/text-field/text-field.ts
// -------------------------------------------------------------------------
// 一个"自制"的表单字段(标签 + 字段 + 帮助 + 字符
// 计数器),像 ngModel 一样支持双向绑定:
//     <app-text-field [(value)]="lastName" label="Last name" [max]="20" />
//
// model() 创建一个与父组件关联的可写 signal:读取它得到
// 父组件的值,写入它(set)会发出 valueChange 事件,
// [( )] 语法再把该事件转为对父组件 signal 的更新。数据
// 因此真正仍归父组件所有。
// =========================================================================

import { Component, input, model } from '@angular/core';

// 由所有实例共享的计数器:每个字段一个唯一标识符,
// 用于关联 <label for> 和 <input id>
let nextNumber = 0;

@Component({
  selector: 'app-text-field',
  template: `
    <div class="mb-3">
      <label class="form-label" [for]="id">{{ label() }}</label>
      <!-- [value]:父组件的值;(input):每次按键都会替换它 -->
      <input class="form-control" [id]="id" [value]="value()" [attr.maxlength]="max()"
             [class.is-invalid]="value().length === max()" (input)="onInput($event)">
      <div class="form-text">{{ help() }} ({{ value().length }} / {{ max() }})</div>
    </div>
  `,
})
export class TextField {
  readonly value = model.required<string>();
  readonly label = input.required<string>();
  readonly max = input.required<number>();
  readonly help = input('');

  protected readonly id = `text-field-${++nextNumber}`;

  protected onInput(event: Event): void {
    this.value.set((event.target as HTMLInputElement).value);
  }
}
  • 第 33 行:[model()] 创建一个可写信号,并与父组件关联。读取它会返回父组件的值;写入它([set],第 41 行)会修改该值并发出事件 [valueChange](模型名称后加 [Change])。因此,使用 [[(value)]="signal"] 进行写入的父组件,其信号会被更新;
  • 第 18 行:一个模块变量(位于类之外)由组件的所有实例共享:一个为每个字段分配唯一标识符的计数器(第 38 行),用于关联 [<label for>] 和 [<input id>];
  • 第 26–27 行:[[value]] 显示父组件的值;[(input)] 在每次按键时替换它(第 41 行)。[[attr.maxlength]] 是对 HTML 的 attribute 绑定(attribute [maxlength]),而不是 property 绑定。

3.2.3. 父组件

// =========================================================================
// 11-outputs-model/src/app/app.ts - 父组件监听其子组件
// -------------------------------------------------------------------------
// 子组件向上传递信息的两种方式:
//   1. 发出事件(output),父组件用 ( ) 监听;
//   2. 在 model() 上使用双向绑定 [( )]:它是输入 [value]
//      + 事件 (valueChange) 的简写。
// =========================================================================

import { Component, computed, signal } from '@angular/core';
import { Counter } from './counter/counter';
import { TextField } from './text-field/text-field';

@Component({
  selector: 'app-root',
  imports: [Counter, TextField],
  templateUrl: './app.html',
})
export class App {
  protected readonly total = signal(0);
  protected readonly message = signal('');
  protected readonly firstName = signal('Marie');
  protected readonly lastName = signal('PELISSIER');
  protected readonly fullName = computed(() => `${this.firstName()} ${this.lastName().toUpperCase()}`);

  // incremented 事件的处理函数:它接收所发出的数据($event)
  protected onChange(label: string, value: number): void {
    this.total.update((t) => t + 1);
    this.message.set(`${label} is now ${value}`);
  }

  protected clear(): void {
    this.firstName.set('');
    this.lastName.set('');
  }
}
<div class="container py-4" style="max-width: 640px">
  <h1 class="h3 mb-3">Example 11 - the outputs of a component and model()</h1>

  <div class="card p-3 mb-4">
    <h2 class="h6">1. Events emitted by the children</h2>
    <!-- $event:子组件发出的数据(此处为新值) -->
    <app-counter label="Coffees" [max]="3" (incremented)="onChange('Coffees', $event)"
                  (limit)="message.set('No more than 3 coffees!')" />
    <app-counter label="Glasses of water" [max]="8" (incremented)="onChange('Glasses of water', $event)"
                  (limit)="message.set('Enough drinking.')" />
    <p class="mb-0">Total clicks: {{ total() }} - <em>{{ message() }}</em></p>
  </div>

  <div class="card p-3">
    <h2 class="h6">2. A two-way binding with model()</h2>
    <!-- [(value)]="firstName":父组件的 firstName signal,由子组件读取并修改 -->
    <app-text-field [(value)]="firstName" label="First name" [max]="20" help="Required" />
    <app-text-field [(value)]="lastName" label="Last name" [max]="20" help="Displayed in upper case" />
    <p class="mb-0">Data of the parent: <strong>{{ fullName() }}</strong></p>
    <button class="btn btn-sm btn-outline-secondary mt-2 align-self-start" (click)="clear()">Clear (from the parent)</button>
  </div>
</div>
  • 第 7 行:[(incremented)="..."] 监听来自计数器的输出 [incremented] ;[$event] 是输出的数据(新值)。[label="Coffees"],不带方括号:字符串类型的输入可以接收常量值;
  • 第 8 行:[(limit)]:信号的方法([set])可以直接在模板中调用;
  • 第 9 行:第二个计数器,有自己的标签、上限和消息;
  • 第 17 行:[[(value)]="firstName"]:父组件的信号 [firstName] (不带括号:指定的是信号本身),由子组件读取并修改。这是 [[value]="firstName()" (valueChange)="firstName.set($event)"] 的简写;
  • 第 20 行:父组件修改自己的数据:两个字段随之更新。

[npm start 11-outputs-model];点击咖啡四次,点击水一次,然后输入姓名:

Image

3.3. 示例 12:内容投影

输入传递数据;内容投影传递内容(来自 HTML 和其他组件),由父组件写在组件标签之间。这相当于 [layout.hbs] 模板在 [NestJS] 课程中的客户端对应物,以及其 [{{{body}}}]。

3.3.1. 卡片

一个可复用的框架(边框、页眉、页脚),其内容由父组件提供:

// =========================================================================
// 12-projection/src/app/card/card.ts - 一个可复用的模板
// -------------------------------------------------------------------------
// 输入传递数据;内容投影传递
// 内容(HTML、其他组件),由父组件写在
// <app-card> 和 </app-card> 标签之间。卡片确定外框(边框,
// 页眉、页脚),父组件提供其中的内容:
//   - <ng-content /> :"主"内容;
//   - <ng-content select="[header]" /> :仅限带有
//                                        header 属性的元素;
//   - 放在 <ng-content> 和 </ng-content> 之间的内容,在
//     父组件未提供任何内容时显示(默认内容)。
// 它是 NestJS 课程中 layout.hbs 模板及其 {{{body}}}
// 在客户端的对应物。
// =========================================================================

import { Component, input } from '@angular/core';

@Component({
  selector: 'app-card',
  template: `
    <div class="card mb-3" [class]="color() ? 'border-' + color() : ''">
      <div class="card-header" [class]="color() ? 'text-bg-' + color() : ''">
        <ng-content select="[header]">Untitled</ng-content>
      </div>
      <div class="card-body">
        <ng-content />
      </div>
      <!-- 空的页脚(父组件未提供任何内容)会被 CSS :empty 隐藏 -->
      <div class="card-footer text-muted small"><ng-content select="[footer]" /></div>
    </div>
  `,
  styles: `
    .card-footer:empty {
      display: none;
    }
  `,
})
export class Card {
  readonly color = input<'primary' | 'success' | 'danger'>();
}
  • 第 27 行:[<ng-content />]:[Angular] 放置父组件写在 [<app-card>] 和 [</app-card>] 之间的内容的位置;
  • 第 24 行:[<ng-content select="[header]">]:仅限具有 [header] 属性的内容元素。[select] 接受 CSS 选择器(标签、类或属性)。[<ng-content>] 和 [</ng-content>] 之间的文本会在父元素未提供任何内容时显示:这就是默认内容;
  • 第 30 行:页脚:具有 [footer] 属性的元素;
  • 第 33–37 行:空的页脚(父元素未提供任何内容)会被隐藏:CSS 伪类 [:empty] 表示没有内容的元素;
  • 第 40 行:一个可选输入,只能取三个值;如果未指定默认值,则默认为 [undefined]。

3.3.2. 泛型数组

一个知道如何遍历各行、但不知道如何显示某一行的数组:其父组件通过向它传递行模板来告诉它如何显示。

// =========================================================================
// 12-projection/src/app/data-table/data-table.ts - 一个泛型表格
// -------------------------------------------------------------------------
// DataTable<T> 是一个泛型类:它显示任意
// 类型 T 的行。它知道如何遍历各行,但不知道如何显示一行:
// 由父组件通过传入行模板来告诉它
// (<ng-template #row>,一段不会按原样显示
// 但可按需显示任意多次的 HTML)。
//
// contentChild('row'):父组件放在 <app-data-table> 和
// </app-data-table> 之间的 <ng-template #row>。表格借助 ngTemplateOutlet
// 为每一行显示它,并向其传入一个上下文:行($implicit)
// 及其序号(index)。因此父组件提供的内容使用的是
// 属于子组件的数据。
// =========================================================================

import { Component, contentChild, input, TemplateRef } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';

// 表格传给每一行模板的内容
export interface RowContext<T> {
  $implicit: T; // 由 let-row 获取的值
  index: number; // 由 let-i="index" 获取
}

@Component({
  selector: 'app-data-table',
  imports: [NgTemplateOutlet],
  template: `
    <table class="table table-sm align-middle mb-0">
      <thead>
        <tr>
          @for (c of columns(); track c) {
            <th>{{ c }}</th>
          }
        </tr>
      </thead>
      <tbody>
        @for (l of rows(); track l.id; let i = $index) {
          <tr>
            <ng-container [ngTemplateOutlet]="rowTemplate() ?? null" [ngTemplateOutletContext]="{ $implicit: l, index: i }" />
          </tr>
        } @empty {
          <tr>
            <td class="text-muted" [attr.colspan]="columns().length">
              <ng-content select="[empty]">No data.</ng-content>
            </td>
          </tr>
        }
      </tbody>
    </table>
  `,
})
export class DataTable<T extends { id: number }> {
  readonly rows = input.required<T[]>();
  readonly columns = input.required<string[]>();
  protected readonly rowTemplate = contentChild<TemplateRef<RowContext<T>>>('row');
}
  • 第 54 行:[DataTable<T>] 是一个泛型类:它可以显示任意类型 [T] 的行,前提是它们具有 [id] (用于 [track],第 39 行);
  • 第 57 行:[contentChild('row')]:一个信号,引用投影内容中标记为 [#row] 的元素。它将是一个 [<ng-template>]:一段不会按原样显示、但可以按需显示任意多次的 HTML(一个 [TemplateRef]);
  • 第 41 行:[ngTemplateOutlet] 指令通过向模板传递一个上下文来显示它——上下文是一个对象,其属性会成为模板中的变量。[$implicit] 是默认值(第 21–24 行);
  • 第 43–49 行:如果列表为空,则显示块 [@empty],包含投影内容([[empty]])和默认内容;
  • 第 45 行:[[attr.colspan]]:attribute 绑定,因为 [colspan] 不是 [<td>] 元素的 property。

3.3.3. 父组件

// =========================================================================
// 12-projection/src/app/app.ts - 使用 Card 和 DataTable 模板
// =========================================================================

import { Component, computed, signal } from '@angular/core';
import { Card } from './card/card';
import { DataTable } from './data-table/data-table';

interface Slot {
  id: number;
  time: string;
  patient: string | null;
}

@Component({
  selector: 'app-root',
  imports: [Card, DataTable],
  templateUrl: './app.html',
})
export class App {
  protected readonly slots = signal<Slot[]>([
    { id: 1, time: '8:00 - 8:20', patient: null },
    { id: 2, time: '8:20 - 8:40', patient: 'Mme Alice DURAND' },
    { id: 3, time: '8:40 - 9:00', patient: null },
  ]);
  protected readonly free = computed(() => this.slots().filter((c) => c.patient === null).length);
  protected readonly nobody: { id: number; name: string }[] = [];
}
<div class="container py-4" style="max-width: 720px">
  <h1 class="h3 mb-3">Example 12 - content projection</h1>

  <app-card color="primary">
    <!-- header 属性:这个 <span> 将进入 <ng-content select="[header]"> -->
    <span header>Schedule of Mme PELISSIER</span>
    <!-- 既没有 header 也没有 footer 的所有内容都进入主 <ng-content /> -->
    <app-data-table [rows]="slots()" [columns]="['#', 'Slot', 'Status']">
      <!-- 行的模板:let-c 接收该行,let-i 接收其序号 -->
      <ng-template #row let-c let-i="index">
        <td>{{ i + 1 }}</td>
        <td>{{ c.time }}</td>
        <td>
          @if (c.patient) {
            <span class="badge text-bg-secondary">{{ c.patient }}</span>
          } @else {
            <span class="badge text-bg-success">Free</span>
          }
        </td>
      </ng-template>
    </app-data-table>
    <span footer>{{ free() }} free slot(s)</span>
  </app-card>

  <app-card color="success">
    <span header>A card without a footer</span>
    <p class="mb-0">The footer is not provided: the card does not display it.</p>
  </app-card>

  <app-card>
    <!-- 未提供 header:默认内容 "Untitled" -->
    <app-data-table [rows]="nobody" [columns]="['Name']">
      <span empty>Nobody for now.</span>
    </app-data-table>
  </app-card>
</div>
  • 第 4–23 行:一张蓝色卡片。其内容由卡片分配:[<span header>] (第 6 行)进入页眉,[<span footer>] (第 22 行)进入页脚,其余部分(表格)进入主体;
  • 第 10–20 行:行的模板。[let-c] 从上下文(该行)中获取值 [$implicit] ,而 [let-i="index"] 获取 其属性 [index]。因此,父组件提供的内容使用的是属于子组件的数据;
  • 第 25–28 行:没有页脚的卡片;
  • 第 30–35 行:没有页眉的卡片(默认内容“Untitled”),以及一个空表格。

[npm start 12-projection]:

Image

编译器无法识别模板中 [c] 的类型(第 10–20 行):它将其视为 [any]。这可以补救(通过声明上下文类型的指令),代价是多写一点代码;这是该技术的局限。

3.4. 示例 13:组件的生命周期

组件会被创建、显示、存在,然后消失。[Angular] 允许你在每个阶段采取行动:这就是组件的生命周期。

3.4.1. 时钟

时钟在创建时启动一个定时器……并且必须在它消失时停止该定时器:否则,定时器会无故继续运行(内存泄漏)。

// =========================================================================
// 13-lifecycle/src/app/clock/clock.ts
// -------------------------------------------------------------------------
// 组件的生命周期:
//   1. constructor :创建类;输入此时
//                         尚不可用;
//   2. ngOnInit :输入已接收到第一个值;
//   3. afterNextRender :组件已显示,其 HTML 元素
//                         已存在于页面中;
//   4. ngOnDestroy :组件即将从页面中移除。
// 时钟在启动时开启一个定时器(setInterval)……并且必须
// 在它消失时务必停止该定时器:否则定时器
// 会白白一直运行下去(内存泄漏)。
// =========================================================================

import { afterNextRender, Component, OnDestroy, OnInit, output, signal } from '@angular/core';

@Component({
  selector: 'app-clock',
  template: `<div class="display-6 font-monospace">{{ time() }}</div>`,
})
// implements OnInit, OnDestroy:TypeScript 检查这些方法是否存在
export class Clock implements OnInit, OnDestroy {
  readonly log = output<string>();
  protected readonly time = signal(new Date().toLocaleTimeString());
  private timer: number | undefined;

  constructor() {
    console.log('Clock: constructor'); // 父组件尚未监听 log
    // afterNextRender 在构造函数中注册;该函数
    // 在组件首次显示之后立即调用一次
    afterNextRender(() => this.log.emit('Clock: afterNextRender - displayed'));
  }

  ngOnInit(): void {
    this.log.emit('Clock: ngOnInit - starting the timer');
    this.timer = window.setInterval(() => this.time.set(new Date().toLocaleTimeString()), 1000);
  }

  ngOnDestroy(): void {
    window.clearInterval(this.timer);
    this.log.emit('Clock: ngOnDestroy - timer stopped');
  }
}

步骤:

  • 第 28–33 行:构造函数:类被创建。输入尚未被赋值,父组件也尚未监听输出(因此第 29 行使用 [console.log] ,而不是 [emit]);
  • 第 35–38 行:[ngOnInit()]:输入已收到其第一个值。这是触发依赖它们的操作的常用位置:加载、定时器;
  • 第 32 行:[afterNextRender(function)],在构造函数中调用,注册一个只执行一次的函数,在组件被首次显示后立即执行:其 HTML 元素此时已存在于页面上;
  • 第 40–43 行:[ngOnDestroy()]:组件即将从页面移除。定时器被停止。

[implements OnInit, OnDestroy] (第 23 行)不是必需的:[Angular] 会调用 [ngOnInit] (如果存在)。但 [TypeScript] 随后会验证这些方法是否书写正确。

[Angular] 提供了其他阶段,自从引入信号以来,它们的用处变小了:[ngOnChanges](某个输入发生了变化;对于该输入,我们更倾向于使用 [computed] 或 [effect] )、[ngAfterViewInit]……以及 [ngOnDestroy]的一种替代方式:[inject(DestroyRef).onDestroy(function)],示例 14 将使用它。

3.4.2. 父组件

// =========================================================================
// 13-lifecycle/src/app/app.ts
// -------------------------------------------------------------------------
//   - <app-clock> 外的 @if:勾选 / 取消勾选复选框会创建 / 销毁
//     该组件(ngOnInit / ngOnDestroy,参见 clock.ts);
//   - viewChild('field'):一个 signal,给出模板中标记为 #field 的
//     HTML 元素(在其显示之前为 undefined);
//   - effect:先执行一次,之后每当其读取的
//     signal 变化时执行。这里用于在字段一出现
//     就给它焦点,并使标签页的标题跟随输入的内容。
// =========================================================================

import { Component, effect, ElementRef, OnInit, signal, viewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Clock } from './clock/clock';

@Component({
  selector: 'app-root',
  imports: [FormsModule, Clock],
  templateUrl: './app.html',
})
export class App implements OnInit {
  protected readonly withClock = signal(true);
  protected readonly log = signal<string[]>([]);
  protected readonly search = signal('');
  protected readonly showSearch = signal(false);

  // 模板中的 <input #field> 元素;ElementRef.nativeElement:HTML 元素
  private readonly field = viewChild<ElementRef<HTMLInputElement>>('field');

  constructor() {
    // 字段出现时(viewChild 变化):让它获得焦点
    effect(() => this.field()?.nativeElement.focus());
    // 标签页的标题从一开始就跟随输入内容
    effect(() => {
      const text = this.search();
      document.title = text ? `Search: ${text}` : 'Example 13';
    });
  }

  ngOnInit(): void {
    this.trace('App: ngOnInit');
  }

  protected trace(message: string): void {
    this.log.update((j) => [...j, `${new Date().toLocaleTimeString()} ${message}`]);
  }
}
  • 第 29 行:[viewChild('field')]:一个信号,引用标记为 [#field] 的模板元素。它被设置为 [undefined] ,只要该元素不存在(该字段仅在点击后才出现)。[ElementRef] 包装 HTML 元素,可通过其属性 [nativeElement]访问;
  • 第 33 行:一个 [effect] 读取该信号:当字段出现时,effect 会再次触发并使其获得焦点。无需“等待”页面刷新:只有在元素创建之后,信号才会改变;
  • 第 35–38 行:第二个 effect:随着文本输入,标签页标题会更新,从一开始就是如此(effect 总是在开始时运行一次);
  • 第 41–43 行:父元素也有它自己的 [ngOnInit]。
<div class="container py-4" style="max-width: 720px">
  <h1 class="h3 mb-3">Example 13 - the lifecycle of a component</h1>

  <div class="card p-3 mb-3">
    <label class="form-check-label mb-2">
      <input type="checkbox" class="form-check-input" [(ngModel)]="withClock"> show the clock
    </label>
    @if (withClock()) {
      <app-clock (log)="trace($event)" />
    }
  </div>

  <div class="card p-3 mb-3">
    @if (!showSearch()) {
      <button class="btn btn-outline-primary align-self-start" (click)="showSearch.set(true)">Search...</button>
    } @else {
      <!-- #field:viewChild('field') 所指向的元素 -->
      <input #field class="form-control" placeholder="the tab title follows what you type" [(ngModel)]="search">
    }
  </div>

  <h2 class="h6">Log</h2>
  <ol class="small">
    @for (line of log(); track $index) {
      <li>{{ line }}</li>
    }
  </ol>
</div>
  • 第 8–10 行:勾选或取消勾选复选框会创建或销毁时钟:[@if] 实际上是在页面中添加或移除该组件;
  • 第 18 行:[#field],即 [viewChild('field')] 所引用的元素。

[npm start 13-lifecycle];取消勾选再重新勾选复选框,然后点击“Search...”:

Image

日志显示了各步骤的顺序:首先是父组件([App: ngOnInit]),然后是时钟([ngOnInit]、[afterNextRender]),接着是它的销毁([ngOnDestroy]),以及一个新的时钟。搜索字段获得了焦点。

3.5. 示例 14:服务与依赖注入

一个服务 是将多个组件共享的数据和代码组合在一起的类:服务器访问、已登录用户、购物车等。组件不会创建服务(绝不要 [new CartService()]):它们会请求这些服务,请求对象是 [Angular],方式是使用 [inject()] 函数。这就是 依赖注入,即 [NestJS] 课程在服务器端介绍过的机制。

当组件请求某个服务时,[Angular] 会查找谁提供了它:先是组件本身,然后是它的父组件,父组件的父组件……一直向上到应用程序。因此,根据提供位置的不同,服务的共享范围有大有小。此示例展示了三个层级。

3.5.1. 根服务

import { Injectable, signal } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class LogService {
  private readonly _lines = signal<string[]>([]);
  // asReadonly():组件只能读取这些行;只有服务才能修改它们
  readonly lines = this._lines.asReadonly();

  trace(message: string): void {
    this._lines.update((l) => [`${new Date().toLocaleTimeString()} ${message}`, ...l].slice(0, 6));
  }
}
  • 第 14 行:[@Injectable({ providedIn: 'root' })]:该服务在应用程序的根 级别提供。[Angular] 在首次请求时创建唯一的实例,所有请求它的组件都会收到该实例;
  • 第 16–18 行:行数据是私有的;[asReadonly()] 提供其公开的只读版本。组件读取这些行;只有服务才会修改它们(第 21 行)。这是维护状态的服务的标准组织方式。

3.5.2. 由组件提供的服务

import { computed, inject, Injectable, signal } from '@angular/core';
import { LogService } from './log.service';

export interface Item {
  label: string;
  price: number;
}

@Injectable()
export class CartService {
  // 服务本身也可以请求其他服务
  private readonly log = inject(LogService);

  private readonly _items = signal<Item[]>([]);
  readonly items = this._items.asReadonly();
  readonly total = computed(() => this._items().reduce((sum, a) => sum + a.price, 0));

  add(item: Item): void {
    this._items.update((a) => [...a, item]);
    this.log.trace(`cart: + ${item.label}`);
  }

  remove(index: number): void {
    this.log.trace(`cart: - ${this._items()[index].label}`);
    this._items.update((a) => a.filter((_, i) => i !== index));
  }
}
  • 第 19 行:[@Injectable()] 不带 [providedIn]:该服务默认不在任何地方提供。组件会在其[providers] 数组中提供它;
  • 第 22 行:服务本身也可以请求其他服务:购物车会被记录日志;
  • 第 24–26 行:购物车的状态(私有)、其只读版本及其总额;
  • 第 28–36 行:修改状态的两个操作。

3.5.3. 已配置的服务

import { DestroyRef, inject, Injectable, InjectionToken, signal } from '@angular/core';

// factory:无人提供此令牌时所使用的值
export const CLOCK_PERIOD = new InjectionToken<number>('period of the clock', { factory: () => 1000 });

@Injectable()
export class ClockService {
  private readonly period = inject(CLOCK_PERIOD);
  readonly now = signal(new Date());

  constructor() {
    const timer = window.setInterval(() => this.now.set(new Date()), this.period);
    inject(DestroyRef).onDestroy(() => window.clearInterval(timer));
  }
}
  • 第 15 行:注入令牌 ([InjectionToken])指代并非类的值:此处是一个数字——时钟周期。[factory] 提供在无人提供此令牌时使用的值;
  • 第 19 行:令牌值的请求方式与服务的请求方式相同;
  • 第 24 行:[DestroyRef] 表示提供该服务的组件的“生命周期”;[onDestroy] 注册一个在其被销毁时执行的函数:定时器会随提供该时钟的组件一同停止。

[inject()] 只能在注入上下文中调用:即在初始化由 [Angular] 创建的类(组件、服务、指令、管道)的属性时,或在其构造函数中。之后不能在普通方法内调用它。

3.5.4. 组件

一个向购物车添加商品的目录:

// 14-services/src/app/catalog/catalog.ts - 注入购物车的后代组件
import { Component, inject } from '@angular/core';
import { Item, CartService } from '../services/cart.service';

@Component({
  selector: 'app-catalog',
  template: `
    <ul class="list-group">
      @for (a of catalog; track a.label) {
        <li class="list-group-item d-flex justify-content-between align-items-center">
          {{ a.label }} (€{{ a.price }})
          <button class="btn btn-sm btn-outline-primary" (click)="cart.add(a)">Add</button>
        </li>
      }
    </ul>
  `,
})
export class Catalog {
  // App 提供的购物车(若无人提供,则在运行时报错)
  protected readonly cart = inject(CartService);

  protected readonly catalog: Item[] = [
    { label: 'Consultation', price: 30 },
    { label: 'Vaccine', price: 12.5 },
    { label: 'Certificate', price: 5 },
  ];
}
  • 第 20 行:[inject(CartService)]:由父组件([App])提供的购物车。如果无人提供,[Angular] 将报告运行时错误;
  • 第 12 行:模板直接调用服务的方法。

购物车摘要:

import { Component, inject } from '@angular/core';
import { DatePipe } from '@angular/common';
import { CartService } from '../services/cart.service';
import { ClockService, CLOCK_PERIOD } from '../services/clock.service';

@Component({
  selector: 'app-cart-summary',
  imports: [DatePipe],
  // 为本组件创建一个新的 ClockService 实例,使用另一个
  // period: { provide: token, useValue: value }
  providers: [ClockService, { provide: CLOCK_PERIOD, useValue: 5000 }],
  template: `
    <div class="card p-3">
      <h2 class="h6">Cart ({{ cart.items().length }} item(s)) - {{ clock.now() | date: 'HH:mm:ss' }}</h2>
      <ul class="mb-2">
        @for (a of cart.items(); track $index) {
          <li>{{ a.label }} <a href="#" (click)="$event.preventDefault(); cart.remove($index)">remove</a></li>
        }
      </ul>
      <strong>Total: €{{ cart.total() }}</strong>
    </div>
  `,
})
export class CartSummary {
  protected readonly cart = inject(CartService);
  protected readonly clock = inject(ClockService);
}
  • 第 18 行:组件提供自己的时钟([ClockService] 的新实例)和另一个时间周期:[{ provide: token, useValue: value }];
  • 第 32–33 行:购物车是 [App] 的购物车(与目录中的相同);时钟则是它自己的。

根组件:

import { Component, inject } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Catalog } from './catalog/catalog';
import { CartSummary } from './cart-summary/cart-summary';
import { ClockService } from './services/clock.service';
import { LogService } from './services/log.service';
import { CartService } from './services/cart.service';

@Component({
  selector: 'app-root',
  imports: [DatePipe, Catalog, CartSummary],
  providers: [CartService, ClockService],
  templateUrl: './app.html',
})
export class App {
  protected readonly clock = inject(ClockService);
  protected readonly log = inject(LogService);
}
  • 第 23 行:[App] 提供一个购物车(由它及其所有后代共享)和一个时钟(默认周期:一秒);
  • 第 28 行:日志,根服务。
<div class="container py-4" style="max-width: 720px">
  <h1 class="h3 mb-3">Example 14 - services and dependency injection</h1>
  <p class="text-muted">Clock of App: {{ clock.now() | date: 'HH:mm:ss' }}</p>
  <div class="row g-3">
    <div class="col-md-6"><app-catalog /></div>
    <div class="col-md-6"><app-cart-summary /></div>
  </div>
  <h2 class="h6 mt-3">Log (LogService)</h2>
  <ul class="small">
    @for (line of log.lines(); track $index) {
      <li>{{ line }}</li>
    }
  </ul>
</div>

[npm start 14-services];添加三件商品,移除一件:

Image

两个定时器的前进速度不同:每个组件收到的是离它最近的实例。而购物车则由目录和摘要两者共享。

在 [Angular] 中,服务是在组件之间共享逻辑和数据的手段(相当于“组合式函数”以及 [provide] / [inject] 在 [Vue.js] 中所起的作用)。示例 20 会把它变成由整个应用程序共享的状态。

3.6. 示例 15:编写自己的指令

组件是一种带有模板的指令 。“单独”的指令没有模板:它附加到现有元素(其宿主)上,以修改其外观或行为。[Angular] 提供了一些指令([ngModel]、[routerLink]、[ngTemplateOutlet]……);你也可以编写自己的指令。下面是三个示例。

3.6.1. 鼠标悬停时高亮元素

// =========================================================================
// 15-directives/src/app/directives/highlight.directive.ts
// -------------------------------------------------------------------------
// 属性指令为现有元素添加行为,
// 自身没有模板:<li appHighlight="gold">。它的选择器是
// CSS 属性选择器([appHighlight])。
// host:指令在携带它的元素上设置的绑定
// (即它的 "host"):
//   - '[style.background-color]' : 元素的一个属性;
//   - '(mouseenter)' : 元素的一个事件。
// =========================================================================

import { Directive, input, signal } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: {
    '[style.background-color]': 'hovered() ? color() : null',
    '[style.transition]': '"background-color 0.2s"',
    '(mouseenter)': 'hovered.set(true)',
    '(mouseleave)': 'hovered.set(false)',
  },
})
export class HighlightDirective {
  // 输入属性与选择器同名:<li appHighlight="gold"> 为其赋值
  readonly color = input('#fff3cd', { alias: 'appHighlight', transform: (c: string) => c || '#fff3cd' });
  protected readonly hovered = signal(false);
}
  • 第 15 行:[@Directive] 而不是 [@Component]:没有模板;
  • 第 16 行:选择器是一个 CSS attribute 选择器:该指令应用于任何具有 attribute [appHighlight] 的元素;
  • 第 17–22 行:[host]:指令应用于其宿主的绑定,写法与模板中相同:
    • 第 18 行:property 绑定:鼠标悬停时宿主的背景颜色([null]:无颜色);
    • 第 20–21 行:事件绑定:鼠标进入和离开;
  • 第 26 行:以选择器命名的输入(选项 [alias]):[<li appHighlight="gold">] 同时填充选择器和输入。 其函数 [transform] 会把空字符串替换为默认颜色。

3.6.2. 设置焦点

// =========================================================================
// 15-directives/src/app/directives/autofocus.directive.ts
// -------------------------------------------------------------------------
// <input appAutofocus>:字段一显示出来就获得焦点。
// inject(ElementRef) 提供宿主 HTML 元素(nativeElement)。
// (HTML 的 autofocus 属性只在页面加载时起作用;
// 在单页应用中,字段是稍后才出现的。)
// =========================================================================

import { afterNextRender, Directive, ElementRef, inject } from '@angular/core';

@Directive({ selector: '[appAutofocus]' })
export class AutofocusDirective {
  constructor() {
    const element = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
    afterNextRender(() => element.focus());
  }
}
  • 第 15 行:[inject(ElementRef)] 指定宿主元素;
  • 第 16 行:元素一显示就会获得焦点。HTML attribute [autofocus] 仅在页面加载时有效;在单页应用中,字段是稍后才出现的。

3.6.3. 长按

指令还可以触发事件。这个指令仅在宿主被按住一秒钟时才触发其事件:这是防止误点击的保护措施。

// =========================================================================
// 15-directives/src/app/directives/long-press.directive.ts
// -------------------------------------------------------------------------
// 指令也可以发出(EMIT)事件(output):
//     <button (appLongPress)="remove()">
// 只有按住按钮一秒钟才会发出该事件:
// 以防误点。按压期间,按钮会被设置
// CSS 类 "pressed"。
// =========================================================================

import { DestroyRef, Directive, inject, input, output, signal } from '@angular/core';

@Directive({
  selector: '[appLongPress]',
  host: {
    '[class.pressed]': 'pressing()',
    '(pointerdown)': 'start()',
    '(pointerup)': 'stop()',
    '(pointerleave)': 'stop()',
  },
})
export class LongPressDirective {
  readonly duration = input(1000); // 以毫秒为单位
  readonly appLongPress = output<void>();
  protected readonly pressing = signal(false);
  private timer: number | undefined;

  constructor() {
    inject(DestroyRef).onDestroy(() => window.clearTimeout(this.timer));
  }

  protected start(): void {
    this.pressing.set(true);
    this.timer = window.setTimeout(() => {
      this.pressing.set(false);
      this.appLongPress.emit();
    }, this.duration());
  }

  protected stop(): void {
    window.clearTimeout(this.timer);
    this.pressing.set(false);
  }
}
  • 第 16 行:当宿主被按下时,类 [pressed] 会应用于宿主;
  • 第 17–19 行:指针事件(鼠标、手指、触控笔):按下、释放、离开元素;
  • 第 24 行:以选择器名称命名的输出:我们写 [(appLongPress)="..."],在监听其事件的同时应用该指令;
  • 第 29 行:如果宿主消失,定时器就会停止。

3.6.4. 用法

// =========================================================================
// 15-directives/src/app/app.ts - 编写自己的指令
// -------------------------------------------------------------------------
// 组件是带模板的指令。“普通”指令
// 没有模板:它附加到现有元素上,
// 以修改其外观或行为。与组件一样,它必须
// 由使用它的组件导入。
// =========================================================================

import { Component, signal } from '@angular/core';
import { AutofocusDirective } from './directives/autofocus.directive';
import { LongPressDirective } from './directives/long-press.directive';
import { HighlightDirective } from './directives/highlight.directive';

@Component({
  selector: 'app-root',
  imports: [AutofocusDirective, LongPressDirective, HighlightDirective],
  templateUrl: './app.html',
  styles: `
    .pressed {
      outline: 4px solid #dc3545;
    }
  `,
})
export class App {
  protected readonly doctors = signal(['Mme Marie PELISSIER', 'Mr Paul TATOU', 'Melle Sophie DUPONT']);
  protected readonly message = signal('');

  protected remove(name: string): void {
    this.doctors.update((m) => m.filter((x) => x !== name));
    this.message.set(`${name} has been deleted.`);
  }
}
  • 第 17 行:与组件一样,指令必须由使用它的组件导入;
  • 第 19–23 行:[pressed] 类的样式,由长按指令设置。
<div class="container py-4" style="max-width: 640px">
  <h1 class="h3 mb-3">Example 15 - writing your own directives</h1>
  <!-- appAutofocus:页面一显示,该字段就获得焦点 -->
  <input appAutofocus class="form-control mb-3" placeholder="this field received the focus by itself">

  <p class="small text-muted">Hover over the rows; hold a button down for one second to delete.</p>
  <ul class="list-group mb-3">
    @for (m of doctors(); track m; let even = $even) {
      <!-- appHighlight:无值时使用默认颜色;有值时使用指定颜色 -->
      <li class="list-group-item d-flex justify-content-between align-items-center"
          [appHighlight]="even ? '' : '#d1e7dd'">
        {{ m }}
        <button class="btn btn-sm btn-outline-danger" (appLongPress)="remove(m)">Delete (long press)</button>
      </li>
    }
  </ul>
  @if (message()) {
    <p class="alert alert-info">{{ message() }}</p>
  }
</div>
  • 第 4 行:字段一显示就会获得焦点;
  • 第 8 行:[let even = $even]:行号是偶数吗?
  • 第 11 行:每隔一行以默认颜色高亮,其余行为绿色;
  • 第 13 行:长按会删除该医生。

[npm start 15-directives];按住第二个按钮,然后将鼠标悬停在第一行上:

Image

3.7. 示例 16:可复用的确认窗口

在删除某一项之前,会请用户确认。浏览器提供了 [window.confirm()],但它的窗口无法设置格式或翻译。本示例用 [Bootstrap] 窗口取代它,综合了前面示例所演示的内容:一个服务 (示例 14),用信号携带窗口的状态;以及一个组件 ,用来显示它。案例研究将使用完全相同的机制。

1
2
3
4
5
6
16-confirmation/src/app/
├── confirmation/
│   ├── confirmation.service.ts   服务:提出的问题及其回答
│   └── confirm-dialog.ts         模态对话框
├── app.ts
└── app.html

3.7.1. 服务

// =========================================================================
// 16-confirmation/src/app/confirmation/confirmation.service.ts
// -------------------------------------------------------------------------
// "Are you sure?":window.confirm() 虽然存在,但既不能
// 设置样式,其按钮也无法翻译。我们用由本服务驱动的
// Bootstrap 对话框(confirm-dialog.ts)取而代之。
//
// 诀窍:confirm(message) 返回一个 PROMISE,用户作出回答时
// 解析为 true(是)或 false(否)。调用代码
// 因此可以写得和 window.confirm 一样简单:
//
//     if (await this.confirmation.confirm('Delete this doctor?')) { ... }
//
// providedIn: 'root':整个应用只有一个服务,因此也只有一个
// 对话框,在根组件中只放置一次。
// =========================================================================

import { Injectable, signal } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ConfirmationService {
  private readonly _message = signal<string | null>(null); // null:对话框关闭
  readonly message = this._message.asReadonly();
  private answer: ((yes: boolean) => void) | null = null;

  confirm(text: string): Promise<boolean> {
    this.answer?.(false); // 还有未回答的问题?视为“否”
    this._message.set(text);
    return new Promise<boolean>((resolve) => {
      this.answer = resolve;
    });
  }

  respond(yes: boolean): void {
    this._message.set(null);
    const r = this.answer;
    this.answer = null;
    r?.(yes);
  }
}
  • 第 20 行:整个应用程序只有一个服务;因此只会有一个窗口,一次性放置在根组件中;
  • 第 22 行:显示的消息;[null] 表示窗口已关闭;
  • 第 23 行:[asReadonly()]:组件可以读取消息,但只有服务才能修改它;
  • 第 24 行:用于解决当前 promise 的函数,该 promise 正在等待响应;
  • 第 26–32 行:[confirm] 打开窗口(第 28 行)并返回一个 promise。它的 [resolve] 函数被保存起来(第 30 行):直到稍后用户点击按钮时,该 promise 才会被解决;
  • 第 27 行:如果还有未关闭的问题,它会被回答为“否”:其 promise 不会永远处于挂起状态;
  • 第 34–39 行:[respond] 由窗口调用:它关闭窗口(第 35 行),然后用用户的响应解决 promise(第 38 行)。

这就是 promise 的好处:提出问题的代码把它写成对 [window.confirm()] 的调用,等待响应时使用 [await],无需回调函数。

3.7.2. 窗口

// =========================================================================
// 16-confirmation/src/app/confirmation/confirm-dialog.ts
// -------------------------------------------------------------------------
// 模态对话框,在根组件中只放置一次:
//   - 使用与真正的模态框相同的 Bootstrap 类(.modal、.modal-backdrop),
//     “静态”显示(show d-block):无需
//     Bootstrap 的 JavaScript;
//   - 键盘:Escape = No;打开时焦点落在 "No" 按钮(
//     最安全的选项)上。
// host 中的 '(document:keydown.escape)':在整个
// DOCUMENT 上监听的事件,而不是在组件元素上。
// =========================================================================

import { Component, effect, ElementRef, inject, viewChild } from '@angular/core';
import { ConfirmationService } from './confirmation.service';

@Component({
  selector: 'app-confirm-dialog',
  host: { '(document:keydown.escape)': 'confirmation.message() !== null && confirmation.respond(false)' },
  template: `
    @if (confirmation.message(); as message) {
      <div class="modal-backdrop fade show"></div>
      <div class="modal fade show d-block" tabindex="-1" role="alertdialog" aria-modal="true"
           (click)="$event.target === $event.currentTarget && confirmation.respond(false)">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">Confirmation</h5>
              <button type="button" class="btn-close" aria-label="Close" (click)="confirmation.respond(false)"></button>
            </div>
            <div class="modal-body">
              <p class="mb-0">{{ message }}</p>
            </div>
            <div class="modal-footer">
              <button #noButton type="button" class="btn btn-secondary" (click)="confirmation.respond(false)">No, go back</button>
              <button type="button" class="btn btn-danger" (click)="confirmation.respond(true)">Yes, confirm</button>
            </div>
          </div>
        </div>
      </div>
    }
  `,
})
export class ConfirmDialog {
  protected readonly confirmation = inject(ConfirmationService);
  private readonly noButton = viewChild<ElementRef<HTMLButtonElement>>('noButton');

  constructor() {
    // 打开时出现 "No" 按钮:它获得焦点
    effect(() => this.noButton()?.nativeElement.focus());
  }
}
  • 第 19 行:[document:keydown.escape]:事件是在整个document上监听的,而不是在组件的元素上。如果有待回答的问题,按 Esc 键会回答“否”;
  • 第 21 行:只有需要显示消息时窗口才会出现;[as message] 为信号的值指定一个名称;
  • 第 22–23 行:真正的 [Bootstrap] 模态框的类,直接显示([show d-block]):[JavaScript] 派生自 [Bootstrap] 是不必要的,因为 [Angular] 决定显示;
  • 第 24 行:点击紧邻对话框(灰色背景上)的区域,即视为回答“否”。[$event.target === $event.currentTarget]:点击发生在[.modal]元素本身,而不是其某个子元素上;
  • 第 35–36 行:两种响应。“否”按钮带有模板变量[#noButton];
  • 第 46 行:[viewChild] (示例 13)以信号的形式返回标记为[#noButton] 的元素:只要窗口处于关闭状态,它就等于[undefined] ;
  • 第 50 行:一个依赖于该信号的 effect:每次打开窗口时,“否”按钮出现,信号随之变化,按钮获得焦点。我们选择“否”这一最安全的响应:误按 Enter 键不会删除任何内容。

3.7.3. 用法

// =========================================================================
// 16-confirmation/src/app/app.ts - 使用确认对话框
// -------------------------------------------------------------------------
// 与 NestJS 课程的示例 21 页面相同(链接、按钮、确认),
// 但完全不需要与服务器往返通信。
// =========================================================================

import { Component, inject, signal } from '@angular/core';
import { ConfirmationService } from './confirmation/confirmation.service';
import { ConfirmDialog } from './confirmation/confirm-dialog';

interface Contact {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  imports: [ConfirmDialog],
  templateUrl: './app.html',
})
export class App {
  private readonly confirmation = inject(ConfirmationService);
  protected readonly contacts = signal<Contact[]>([
    { id: 1, name: 'Jean MARTIN' },
    { id: 2, name: 'Alice DURAND' },
    { id: 3, name: 'Luc GERMAN' },
  ]);
  protected readonly message = signal('');

  // 异步方法:它“等待”用户的回答
  protected async remove(c: Contact): Promise<void> {
    if (!(await this.confirmation.confirm(`Delete the contact ${c.name}?`))) {
      this.message.set('Deletion cancelled.');
      return;
    }
    this.contacts.update((list) => list.filter((x) => x.id !== c.id));
    this.message.set(`${c.name} has been deleted.`);
  }

  protected async removeAll(): Promise<void> {
    if (await this.confirmation.confirm(`Delete the ${this.contacts().length} contacts?`)) {
      this.contacts.set([]);
      this.message.set('All the contacts have been deleted.');
    }
  }
}
  • 第 19 行:根组件导入该窗口,并将其放置在自己的模板中;
  • 第 23 行:它请求该服务;
  • 第 32–39 行:一个名为[async]的方法。在第 33 行,[await] 会挂起执行,直到用户作出响应;在此期间,应用程序保持活动状态。只有当响应为“是”时,方法的其余部分才会执行;
  • 第 41–46 行:同样的原理也适用于删除所有联系人。
<div class="container py-4" style="max-width: 640px">
  <h1 class="h3 mb-3">Example 16 - a confirmation dialog</h1>
  <ul class="list-group mb-3">
    @for (c of contacts(); track c.id) {
      <li class="list-group-item d-flex justify-content-between align-items-center">
        {{ c.name }}
        <button class="btn btn-sm btn-outline-danger" (click)="remove(c)">Delete</button>
      </li>
    } @empty {
      <li class="list-group-item text-muted">No contact.</li>
    }
  </ul>
  <button class="btn btn-danger" [disabled]="contacts().length === 0" (click)="removeAll()">Delete all</button>
  @if (message()) {
    <p class="alert alert-info mt-3">{{ message() }}</p>
  }
</div>
<!-- 对话框,整个应用只有一个 -->
<app-confirm-dialog />
  • 第 4–11 行:[@for] 后面可以跟一个[@empty]块,在列表为空时显示;
  • 第 13 行:当没有可删除的内容时,该按钮被禁用;
  • 第 19 行:整个应用程序只放置一次的窗口。之后任何组件只需调用该服务即可打开它。

[npm start 16-confirmation];点击 Alice DURAND 的 [Delete] 按钮:

Image

在 [Vue.js]中,窗口及其状态由“组合式函数”提供;在 [Angular]中,则由服务提供。原理是相同的:一个共享状态,存放在信号中,由多个组件读取和修改。