复习一遍最新版本的 Angular

作为前端三大框架之一的 Angular 因为其过高的上手难度一直被忽视,自从 ng1 以后 vue 占领了全国(大概2016年开始?),我就很久没有再去了解过这个项目了。最近因为沉迷 Factorio 建厂,突发奇想想自己用 Nextjs 写一个量化计算器,github 搜参考搜出个很好用的东西 factoriolab,一看是 ng 写的顿时来了兴趣,立马跑到 ng 官网看 getting started 了,现在重新学习一遍,总结一些知识点

  • 基于组件开发应用,组件的结构为树形层级结构,每个组件有一个 template 用于写HTML,组件可以嵌套,组件只有一个根,这一点三个框架都是一致的
  • 组件拥有 metadata,作为组件的 property 存在,定义组件的一些配置
  • 提供了一些快捷命令生成文件,想起 Laravel 的 php artisan gen:ooxx
    • 组件 ng generate component housingLocation --inline-template --skip-tests,快速生成一个组件
    • 接口 ng generate interface housinglocation, 帮你生成一份 TS 的 interface
    • ng generate service housing --skip-tests 创建 service
  • ⭐重要功能 1 在父组件到子组件之间共享数据使用 @Input 属性,@Output 则是让子组件传递数据到父组件,这个重要的技能让你可以开始 动态渲染 前端数据了,很多人第一次学习前端框架触发心流的地方之一吧,笑
  • ⭐重要功能 2 批量渲染动态数据使用指令 *ngfor,这个功能也是所有切图仔在各类 xx管理系统 中渲染表格离不开的东西
  • ⭐重要功能 3 Angular services & 依赖注入 Dependency injection(简称 DI),DI 这个概念以前有一段时间很流行,在各大后端框架中传染开来,像 PHP 的 Laravel 就深受 Java Spring 影响也搞了一个服务容器,不过这个东西大部分人用是会用,但是真的要解释清楚十个人里面九个人说不清,之前在知乎看过一篇文章解释的非常好,不过就算止步于“不用 new 对象了!”这一层理解其实也够了,后来 Golang 流行开以后还有写 Java 的在知乎问为什么 Golang 没有 DI
  • Angular 中的 service 作用是作为提供数据给应用组件的过程 process,数据的来源不做假设,可以是 local,也可以来源 web service

组件一般长这个样子,@Component 表示一个装饰器,内部的对象是 metadata,表示 property

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HousingLocationComponent } from '../housing-location/housing-location.component';
import { HousingLocation } from '../housinglocation';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [
    CommonModule,
    HousingLocationComponent
  ],
  template: `
  <section>
    <form>
      <input type="text" placeholder="Filter by city">
      <button class="primary" type="button">Search</button>
    </form>
  </section>
  <section class="results">
    <app-housing-location></app-housing-location>
  </section>
  `,
  styleUrls: ['./home.component.css'],
})

export class HomeComponent {
  readonly baseUrl = 'https://angular.io/assets/images/tutorials/faa';

  housingLocation: HousingLocation = {
    id: 9999,
    name: 'Test Home',
    city: 'Test city',
    state: 'ST',
    photo: `${this.baseUrl}/example-house.jpg`,
    availableUnits: 99,
    wifi: true,
    laundry: false,
  };
}

posted @ 2024-03-15 03:43  我听不见  阅读(9)  评论(0编辑  收藏  举报