全书目录

第二十六篇:Angular 完全指南 —— 企业中控园区宇宙

第二章:Component —— 园区里的每一栋楼,都是一个职责明确的功能单元

1 分钟 196 字 第 463 / 962 个阅读单元

Angular 的基本建筑单元是 Component

你可以把它理解成园区里的一栋楼:

  • 有楼名:selector
  • 有楼内布局:template
  • 有楼内运行规则:类里的字段和方法
  • 有自己依赖的设施:imports
  • 可能有自己的独立服务窗口:providers
ts
import { Component } from '@angular/core';

@Component({
  selector: 'campus-gate',
  standalone: true,
  template: `
    <section class="gate">
      <h2>{{ title }}</h2>
      <button (click)="toggle()">
        {{ open ? '关闭闸机' : '打开闸机' }}
      </button>
    </section>
  `,
})
export class GateComponent {
  title = '企业中控园区北门';
  open = false;

  toggle() {
    this.open = !this.open;
  }
}

这个组件里最重要的心智不是“类 + HTML”,而是:

text
Component = 一块有边界的业务视图单元
           = 一栋楼
           = 一组模板 + 状态 + 交互 + 依赖声明

Angular 很强调这种边界感,因为企业项目最怕“所有逻辑都糊成一大片”。