即将到来的 Angular 14 的 7 大变化

16,375

前段时间结束的 Google I/O 2022 开发者大会提到一些 Angular 的展望,Angular 14 将于 2022 年 6 月发布,本文将通过 7 个关键点,带你来看 14 版本的变化。

Ivy 引擎

Angular 团队基于更好、更高效的 Lvy 渲染引擎重写了 Angular 的运行时和编辑器。

Lvy 会带来那些新的优势:

  • 更加强调 tree-shaking,改进了类型检查、错误报告,优化了调试系统,减少了打包后的大小。
  • 可使用 VSCode 提供的 Angular Language Service 插件
  • Angular 开发工具浏览器扩展

Lvy 引擎非常重视 tree-shaking 功能, tree-shaking 是指通过 TypeScript 编译器检查代码所需的库,然后删除不必要的代码。

Standalone 组件

Standalone 组件的目标是减少模板文件,使 Angular 更易于使用和学习,同时可以在无 NgModules 的情况下构建组件和应用程序

Standalone 组件是 Angular 的主要功能之一。该组件没有在任何现有的 NgModule 中定义,不依赖于 NgModule,你可以直接依赖它,而不需要中间 NgModule,很多情况下,它可以减少模板文件。具体使用如下:

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

@Component({
    standalone: true,
    template: `Standalone component!`
})
export class LonelyComponent {}

使用 @Component 装饰器将 standalone 标志设置为 true,来构建 Standalone 组件。

新入门途径

Angualr 的学习路径非常陡峭,鉴于此情况,Angular 为初学者重新设计了一条学习路径。

image.png

Typescript 支持

Angular 在 Angular 模板中添加了对类型化表单的支持,该功能将增强类型检查和错误报告。

下面是 Angualr 提供的案例,如果你给 firstName 赋值为数字,会立刻收到一个 TypeScript 错误: TS error: Argument of type ‘10’ is not assignable to parameter of type ‘string | null..

import { Component } from '@angular/core'; 
import { FormControl, FormGroup } from '@angular/forms'; 
@Component({ 
     selector: 'profile', 
     templateUrl: './profile.component.html', 
     styleUrls: ['./profile.component.css'], 
}) 
export class ProfileComponent { 
    profileForm = new FormGroup({ 
        firstName: new FormControl('Mark'), 
        lastName: new FormControl('Doe'), 
 }); 
populate() { 
     // TS error: Argument of type '10' is not assignable to parameter of type 'string | null'. 
     this.profileForm.controls.firstName.setValue(10); 
     } 
 } 

image.png

这非常强大,populate()方法并没有执行,但 TypeScript 还是检查出类型错误。

可扩展性

尽管 Angular 是一个非常"固执"的框架,但仍然可以支持多种需求:

  • 独立开发者: 利用 CLI 可以简单的创建 Angular 应用程序、组件和其他模块;Standalone 无需很多模板也可以轻松创建组件。
  • 初创公司: 利用 Angular Language Service 插件,开发人员可以生成一致的代码,通过类型检测和其他工具,开发人员可以在部署前发现错误。
  • 中型公司: Angular 目前已经支持国际化和渐进式 Web 应用程序(PWA)
  • 大型公司: 微前端

改进可访问性

该功能允许更轻松地定义独特的页面标题,解决了 Web 框架中最常见的可访问性问题。

使用 a11y 服务,可以创建独特、简短的页面名称,帮助人们更好的理解网页的内容,此外标题对视觉障碍用户至关重要。

Angular 14 中,路由器提供一种新的方法来保证页面的唯一名称。

const routes: Routes = [
    { path: 'shop', component: HomeComponent, title: 'Home - CompanyName' },
    { path: 'about', component: ShopComponent, title: 'Shop - CompanyName' },
    { path: 'locate', component: ContactsComponent, title: 'Contacts - CompanyName' },
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: '**', component: HomeComponent },
]

新命令

Angular 提供了两个新的 CLI 指令:

  • ng analytics:控制和打印分析设置的方法
  • ng cache:控制和打印缓存信息的方法