search
HomeWeb Front-endJS TutorialFeature introduction of Angular 5.0

Feature introduction of Angular 5.0

Dec 19, 2017 pm 05:15 PM
angularintroducecharacteristic

We are happy to announce the release of Angular 5.0.0 - Pentagon Donut! This is another major version, containing new features and fixing many bugs. It once again reflects our consistent goal of making Angular smaller, faster, and better to use. Angular 5.0 is here! With these major changes, this article introduces the major changes in Angular 5.0. Interested friends can refer to it. I hope it can help you.


#The following is a brief introduction to the major changes in v5. To learn more, see the changelog.

Build Optimizer

Starting in 5.0.0, product builds executed via the CLI use the build optimizer by default.

The build optimizer is a tool in the CLI that can make the built package smaller based on our understanding of your Angular application.

Building an optimizer has two main tasks. First, mark certain parts of your application as pure so that existing tools can use it to improve the optimization effect of "tree shaking" and remove unnecessary things from the application.

Secondly, the build optimizer will remove Angular decorator code from your app. Decorators are only used by the compiler and are not used during runtime and can be deleted. Both of the above optimizations can reduce the size of the generated JS package and speed up application startup.

Angular Universal state transfer API and support for DOM

This makes it easier to share application state between the server and the client.

Angular Universal is a project that helps developers perform server-side rendering (SSR). The HTML generated by server-side rendering is friendly to spiders and crawlers that do not support JS, and helps improve user-perceived performance.

In 5.0.0, the development team added ServerTransferStateModule and the corresponding BrowserTransferStateModule. This module can help developers add relevant information to the content generated by server-side rendering and then send it to the client to avoid repeated generation. This is useful for scenarios where data is retrieved via HTTP. By transferring status from the server to the client, the developer does not have to make a second HTTP request. Documentation for the status transfer will be released in a few weeks.

The Angular Universal team also added the platform server Domino to the platform server. Domino supports more out-of-the-box DOM operations in a server-side environment, which can improve our support for non-server-side third-party JS and component libraries.

Compiler improvements

To support incremental compilation, we have improved the Angular compiler. As a result, rebuilding is accelerated, especially for product builds and AOT builds, and the effect is more obvious. We also enhanced the decorator to reduce package size by removing whitespace.

TypeScript conversion

Now, the underlying working mechanism of the Angular compiler is TypeScript conversion, making incremental rebuilds much faster. TypeScript conversion is a new feature of TypeScript 2.3 that allows us to dive into the standard TypeScript compilation pipeline.

With the AOT tag open, you can use the above mechanism by running ng serve.

ng serve --aot

I suggest everyone give it a try. This configuration will become the default for the CLI in the future. Many projects have performance issues involving thousands of components, and we hope projects of all sizes can benefit from these improvements.

When performing an incremental AOT build of https://angular.io, the new compiler pipeline can save 95% of the build time (test results on our development machine are from more than 40 seconds reduced to less than 2 seconds).

Our goal is to make AOT compilation fast enough for developers to use it for development. Now, we have broken into under 2 seconds, so AOT may be enabled by default in future CLIs.

As a transition step to this conversion, we no longer need genDir, and outDir has also changed: now, we will type all the files generated for the package into node_modules.

Keep whitespace

In the past the compiler would faithfully reproduce and include tabs, newlines, and whitespace in templates. You can now choose whether to include whitespace in components and applications.

This configuration can be specified in the decorator of each component, and the current default value is true.


@Component({
 templateUrl: 'about.component.html',
 preserveWhitespaces: false
}
export class AboutComponent {}

Or you can configure it globally in tsconfig.json, where the default value is also true.


{
 "extends": "../tsconfig.json",
 "compilerOptions": {
  "outDir": "../out-tsc/app",
  "baseUrl": "./",
  "module": "es2015",
  "types": []
 },
 "angularCompilerOptions": {
  "preserveWhitespaces": false
 },
 "exclude": [
  "test.ts",
  "**/*.spec.ts"
 ]
}

The general rule is that component-level configuration should override application-level configuration. The development team plans to change the default value to false in the future to save space for developers by default. Don't worry about your

 tags, the compiler will handle them intelligently. <p><strong>Improved decorator support</strong></p><p>Expression lowering in Lambda and object literal useValue, useFactory and data decorators is now supported. This makes it possible to use values ​​that can only be lowered in decorators that can be evaluated at runtime. </p><p>So now you can use Lambda functions instead of named functions. In other words, executing the code will not affect your d.ts or your external API. </p><p class="jb51code"><br></p><pre class='brush:php;toolbar:false;'>Component({
 provider: [{provide: SOME_TOKEN, useFactory: () => null}]
})
export class MyClass {}

我们还会将表达式降级,作为useValue的一部分。


Component({
 provider: [{provide: SOME_TOKEN, useValue: SomeEnum.OK}]
})
export class MyClass {}

国际化的数值、日期和货币管道

我们写了新的数值、日期和货币管道,让跨浏览器国际化更方便,不需要再使用i18n的腻子脚本(polyfill)。

在以前版本的Angular中,我们一直依赖浏览器及其i18n API提供数值、日期和货币格式。为此,很多开发者都在使用腻子脚本(polyfill),而结果也不好。很多人反馈说一些常见的格式(如货币)不能做到开箱即用。

而在5.0.0中,我们把这个管道更新成了自己的实现,依赖CLDR提供广泛的地区支持,而且可配置。以下是我们对v4和v5所做的比较:a document comparing the pipe behavior between v4 and v5。

如果你还没条件使用新管理,可以导入DeprecatedI18NPipesModule以降级到旧的行为。

StaticInjector代替ReflectiveInjector

为了消除对更多腻子脚本(polyfill)的依赖,我们用StaticInjector代替了ReflectiveInjector。前者不再需要Reflect,为开发者减少了应用大小。

以前

ReflectiveInjector.resolveAndCreate(providers);

以后

Injector.create(providers);

提升Zone的速度

一方面提升了Zone的速度,另一方面也可以在特别关注性能的应用中绕过它。

若要绕过它,启动应用时加上noop:

platformBrowserDynamic().bootstrapModule(AppModule, {ngZone: 'noop'}).then( ref => {} );

这里有一个完整的例子:the example ng-component-state project。

exportAs

组件和指令中增加了对多名称的支持。这有助于用户实现无痛迁移。通过把指令导出为多个名称,可以在不破坏原有代码的情况下在Angular语法中使用新名称。Angular Material项目已经在其前缀迁移项目中用上了,对其他组件作者肯定也有用。

示例


@Component({
 moduleId: module.id,
 selector: &#39;a[mat-button], a[mat-raised-button], a[mat-icon-button], a[mat-fab], a[mat-mini-fab]&#39;,
 exportAs: &#39;matButton, matAnchor&#39;,
 .
 .
 .
}

HttpClient

v4.3在@angular/common中推出过HttpClient,用于在Angular中发送请求,它小巧易用。HttpClient受到了开发者的广泛赞誉,因此我们推荐在所有应用中使用它,放弃之前的@angular/http library。

要升级HttpClient,需要在每个模块的@angular/common/http中把HttpModule替换为HttpClientModule,注入HttpClient服务,删除所有map(res => res.json())。

CLI v1.5

从Angluar CLI v1.5开始,已经开始支持Angluar v5.0.0,默认生成v5项目。

在这次小版本升级中,我们默认打开了构建优化器,让开发者拿到更小的包。

我们还修改了使用.tsconfig文件的方式,以更严格地遵守TypeScript标准。此前,如果检测到延迟加载的路由,而且你在tsconfig.json中手工指定了一组files或include,那这些路由会自动化处理。而如今,根据TypeScript规范,我们不再这么干了。默认情况下,CLI对TypeScript的配置中没有files或include,因此多数开发者不会受影响。

Angular表单添加updateOn Blur/Submit

这样可以根据blur或submit来运行验证和更新值的逻辑了,不必再单纯依赖input事件。

表单对应用很重要,如果有服务端验证,或者验证或更新值会触发较慢的操作,你当然希望它少跑几次。现在你可以在控件层面控制验证和更新值的时机了,也可以在表单层面设置。

此外,你现在可以直接在选项中指定asyncValidators,而不是通过第三个参数指定。

模板驱动的表单

以前

以后


<input name="firstName" ngModel [ngModelOptions]="{updateOn: &#39;blur&#39;}">

或者


<form [ngFormOptions]="{updateOn:&#39;submit&#39;}">

反应式表单

以前


new FormGroup(value);
new FormControl(value, [], [myValidator])

以后


new FormGroup(value, {updateOn: &#39;blur&#39;}));
new FormControl(value, {updateOn: &#39;blur&#39;, asyncValidators: [myValidator]})

RxJS 5.5

我们已经把使用的RxJS更新到5.5.2或更高版本。这个新发布的RxJS可以让开发完全摆脱之前导入机制的副作用,因为我们以新的lettable operators的方式使用了RxJS。这些新操作符消除了副作用,以及之前导入操作符中“patch”方法存在代码切割和“tree shaking”等问题。

不再这样:


import { Observable } from &#39;rxjs/Observable&#39;;
import &#39;rxjs/add/operator/map&#39;;
import &#39;rxjs/add/operator/filter&#39;;
names = allUserData
.map(user => user.name)
.filter(name => name);

现在这样:


import { Observable } from &#39;rxjs/Observable&#39;;
import { map, filter } from &#39;rxjs/operators&#39;;
names = allUserData.pipe(
 map(user => user.name),
 filter(name => name),
);

此外,RxJS现在发行了一个使用ECMAScript Modules的版本。新Angular CLI会默认拉取这个新版本,让包大小有明显减小。如果你没使用Angular CLI,那还是应该指向这个新版本。相关文档在此:Build and Treeshaking。

新的路由器生成周期事件

我们给路由器添加了新的生命周期事件,让开发者可以跟踪running guard启动到激活完成的各个阶段。这些事件可在有子组件更新时,在一个特定的路由器出口上展示加载动画,或者测量性能。

新的事件(按顺序)是GuardsCheckStart、ChildActivationStart、ActivationStart、GuardsCheckEnd、ResolveStart、ResolveEnd、ActivationEnd、ChildActivationEnd。以下是一个使用这些事件启动和停止加载动画的示例:


class MyComponent {
 constructor(public router: Router, spinner: Spinner) {
  router.events.subscribe(e => {
   if (e instanceof ChildActivationStart) {
    spinner.start(e.route);
   } else if (e instanceof ChildActivationEnd) {
    spinner.end(e.route);
   }
  });
 }
}

如何更新

这里有Angular Update Guide,告诉你整个过程,以及更新前要做哪些事,还有更新应用的步骤,以及做好迎接Angular未来版本的准备等信息。

我们删除很多以前废弃的API(如OpaqueToken),也公布了一些新的废弃项。以上指南会详细介绍这些变更。

相关推荐:

详解Angular中支持SCSS的方法

Angular4表单响应功能示例分析

angularJS的一些用法

The above is the detailed content of Feature introduction of Angular 5.0. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor