Home  >  Article  >  Web Front-end  >  This article will give you an in-depth understanding of Angular11

This article will give you an in-depth understanding of Angular11

青灯夜游
青灯夜游forward
2021-05-24 10:28:513080browse

This article introduces Angular11 to you. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

This article will give you an in-depth understanding of Angular11

## 

Angular has experienced a leap in development from version 1.0 to 2.0. Combined with the powerful tool TypeScript, Angular is becoming an important option for large-scale front-ends. , this question mainly introduces the basic concepts of Anguar 10, and helps readers to get started quickly through the corresponding code. [Related recommendations: "angular Tutorial"]


1. Angular Development Milestone

AngularJS was originally developed by Misko Hevery and Adam Abrons A personal project developed in his spare time in 2009. The original project name was GetAngular. The design goal was to allow web designers (non-developers) to create simple applications using only HTML tags. Over time, AngularJS evolved into a comprehensive development framework. In 2010, in order to promote the development speed of Google Feedback and the progress of the project, Misko Hevery reconstructed Google Feedbac based on GWT, compressing the original more than 17,000 lines of code to only more than 1,500 lines. Since then, Angularjs has attracted attention, and AngularJS has transformed into Google company projects.

Angular1.0 introduces the concept of two-way data binding. In 2016, Microsoft and Google cooperated and adopted TypeScript as a new development language and released Angular 2.0. Angular2.0 and Angularjs1.x are completely different architectures. Angular2.0 and later versions are collectively called Angular2. The user group of Angular1.x is also relatively large, and the corresponding version framework continues to be maintained. The latest version is 1.8.2. The latest version of Angular2 is 11.0.0.

This article will give you an in-depth understanding of Angular11

2. Development overview

##2.1 Two-way data binding  In conventional front-end development, data and views are often related through single binding. The advantage of this model is that the results are relatively simple. The model is responsible for updating data and rendering combined with the template, and the view layer is only responsible for display. The disadvantage of this structure is that data changes in the view layer cannot be fed back to the model layer, which cannot meet the needs of highly interactive pages. This is when two-way data binding comes into being.

#Figure 1 One-way data BindingFigure 2 Two-way data binding

2.2 Core Feature Changes

Angularjs Two-way Binding Method—Dirty Check:

watch = {
    /**  当前的watch对象观测的数据名  **/
    name: ‘’,
    /** 得到新值 **/    
   getNewValue: function($scope) {
       ...
        return newValue;
    },
    /**  当数据发生改变时需要执行的操作  **/
    listener: function(newValue, oldValue) {
        ...
    }
}

Any native Events will not trigger dirty checks, you must call <span class="katex--inline"><span class="katex"><span class="katex-html"><span class="base"><span class="mord mathdefault">s</span><span class="mord mathdefault">c</span><span class="mord mathdefault">o</span><span class="mord mathdefault">p </span><span class="mord mathdefault">e</span><span class="mord">.</span></span></span></span></span>applyNotify angular to update the UI.

Angular two-way binding method—monkey patch

function patchThen(Ctor: Function) {
      ...
      const originalThen = proto.then;
      proto[symbolThen] = originalThen;
      Ctor.prototype.then = function(onResolve: any, onReject: any) {
      		const wrapped = new ZoneAwarePromise((resolve, reject) => {
      			originalThen.call(this, resolve, reject);
      		});
      		return wrapped.then(onResolve, onReject);
      };
      ...
}

  Angular2 has Zone.js. Natively, setTimeout, addEventListener, promise, etc. are all executed in ngZone. Angular has set up corresponding hooks in ngZone, notifies angular2 to do the corresponding dirty check processing, and then updates the DOM.

3. Basic concepts

  • Module
  • Component
  • Template
  • Metadata
  • Data Binding
  • Directive
  • Service
  • Dependency Injection (dependency injection)

3.1 Module (module)

  • Application modularization
  • Module It is a code block with tight functions and has at least one root module NgModule (AppModule)
// src/app/app.module.ts
import { NgModule }      from &#39;@angular/core&#39;;
import { BrowserModule } from &#39;@angular/platform-browser&#39;;
@NgModule({
 imports:      [ BrowserModule ],
 providers:    [ Logger ],
 declarations: [ AppComponent ],
 exports:      [ AppComponent ],
 bootstrap:    [ AppComponent ]
})
export class AppModule { }

3.2 Component

  • The component controls a small area on the screen called the view
  • Define the application logic of the component in a class (mainly used to support the view). Classes and views interact through an API of properties and methods
  • Performs the creation, update, and destruction of components through life cycle hooks
// src/app/hero-list.component.ts (class)
export class HeroListComponent implements OnInit {
 heroes: Hero[];
 selectedHero: Hero;

 constructor(private service: HeroService) { }

 ngOnInit() {
   this.heroes = this.service.getHeroes();
 }

 selectHero(hero: Hero) { this.selectedHero = hero; }
}
// src/app/hero-list.component.html
<li *ngFor="let hero of heroes" (click)="onSelect(hero)">

3.3 Template )

  • Tell Angular in the form of HTML how to render the component
  • HTML with Angular commands (NgClass, NgStyle, NgIf, NgFor...)
  • Custom component
// src/app/hero-list.component.html
<h2>Hero List</h2>

<p><i>Pick a hero from the list</i></p>
<ul>
 <li *ngFor="let hero of heroes" (click)="selectHero(hero)">
   {{hero.name}}
 </li>
</ul>

<app-hero-detail *ngIf="selectedHero" [hero]="selectedHero"></app-hero-detail>

3.4 Metadata

  • Metadata determines that a class in Angular is a component
  • The simple way to attach metadata with TypeScript is to use a decorator
  • @Component function accepts the configuration object and converts it into metadata
  • Templates, metadata and components control the view together
  • Commonly used decorators: @Injectable @Input @Output @RouterConfig
// src/app/hero-list.component.ts (metadata)

@Component({
 selector:    'app-hero-list',
 templateUrl: './hero-list.component.html',
 providers:  [ HeroService ]
})
export class HeroListComponent implements OnInit {
/* . . . */
}

3.5 Data Binding

  • Push data values ​​to HTML controls, and convert responses from users into actions and updates to values
  • Communication between templates and parent-child components
Column 1 Column 2
#Two-way binding Several formsAttribute binding and event bindingTemplate nesting
// src/app/hero-list.component.html (binding)

<li>{{hero.name}}</li>
<app-hero-detail [hero]="selectedHero"></app-hero-detail>
<li (click)="selectHero(hero)"></li>

3.6 Directive(指令)

  • 带有@Directive() 装饰器的类,指示对DOM进行转换
  • 结构型指令和属性型指令
    结构型指令:通过添加、移除或者替换DOM元素来修改布局
// src/app/hero-list.component.html (structural)

<li *ngFor="let hero of heroes"></li>
<app-hero-detail *ngIf="selectedHero"></app-hero-detail>

属性型指令:修改现有元素的外观或行为

// src/app/hero-detail.component.html (ngModel)

<input [(ngModel)]="hero.name">

3.7 Service(服务)

  • 广义:包括应用所需的任何值、函数或特性,狭义:明确定义了用途的类
  • @Injectable() 装饰器来提供元数据
// src/app/logger.service.ts (class)

export class Logger {
   log(msg: any)   { console.log(msg); }
   error(msg: any) { console.error(msg); }
   warn(msg: any)  { console.warn(msg); }
}
// src/app/hero.service.ts (class)

export class HeroService {
 private heroes: Hero[] = [];

 constructor(
   private backend: BackendService,
   private logger: Logger) { }

 getHeroes() {
   this.backend.getAll(Hero).then( (heroes: Hero[]) => {
     this.logger.log(`Fetched ${heroes.length} heroes.`);
     this.heroes.push(...heroes); // fill cache
   });
   return this.heroes;
 }
}

3.8 Dependency Injection(依赖注入)

  • 为一个类的实例提供全部依赖的方法,大部分依赖是服务
  • 全应用级别注入器机制
  • 注入前必须注册一个提供者(Provider),然后返回服务类本身
    全局注册
@Injectable({
   providedIn: &#39;root&#39;,
})

特定注册

@NgModule({
   providers: [
      BackendService,
      Logger
    ],
    ...
})

注入

// src/app/hero-list.component.ts (component providers)

@Component({
   selector:    'app-hero-list',
   templateUrl: './hero-list.component.html',
   providers:  [ HeroService ]
})

四、创建第一Angular项目

4.1 基于Angular CLI

  • 安装Node.js 的当前版、活跃 LTS 版或维护期 LTS版
  • 安装Angular CLI
npm install -g @angular/cli
  • 创作工作空间和初始应用
npm new my-app
  • 运行应用
cd my-app
ng server --open

4.2 基于Angular Quickstart

  • 克隆Quickstart项目
git clone https://github.com/angular/quickstart.git my-app
  • 进入项目并安装依赖
cd ./my-app
npm run install
  • 启动项目
npm start

五、对比VUE

5.1 技术对比

This article will give you an in-depth understanding of Angular11 This article will give you an in-depth understanding of Angular11 Column 2
主要点 Angular VUE
设计目标 全面的解决方案(浏览器端、服务端、客户端),基本包含了开发全流程 渐进增强,扩展性强,用户选择余地大
组件 组件是ng2+应用核心,支持Web Component标准,组件生命周期明确 完善的组件系统,可以从template生成或者render渲染,组件有明确的生命周期,使用virtual dom渲染
异步处理 原生支持RxJS,通过流模型处理异步任务 没有官方异步处理方案,可以用Promise,也可以用RxJS染
构建部署 支持Just In Time(JIT)和Ahead Of Time(AOT)模式,配合tree shaking可以大幅减少代码体积 配合Webpack打包工具,在不引入组件的情况下,体积更小
状态管理 ngrx vuex
安全 对不信值进行编码,避免XSS攻击,使用离线模版编译器,防止模版注入。官方http库防止XSRF 没有强制性阻止XSS攻击机制,输出HTML要注意配合v-html指令
优点 框架对几乎任何场景,都提供了标准化,更工程化,更适合大型项目多人协作面向新特性,发展空间大 框架可被不同程度的使用,可单独使用核心,也可加入状态管理,提供了更多选项。适合初期快速迭代,性能上没有很大缺陷
缺点 使用大量第三方库和组件,增加了潜在风险,应用性能可控性降低 由于提供了开发选项,多人协作下,对与使用程度和场景的处理可能不一样,随着项目增大,以快为特点的技术,在工程化和代码管理上可能存在困难。需要程序员手动实现类似依赖注入的功能、代码组织
选型 业务要求稳定、能够增量开发的项目 快速迭代、可以被替换的项目

5.2 开源组件库资源对比

Angular Vue
Angular Material2 Element UI
DEVUI Mint UI
PrimeNg iView UI
Kendo UI Bootstrap-Vue UI
Ng-lightning Ant Design Vue UI
Ng-bootstrap AT-UI UI
NG-ZORRO cube-ui UI
NGX Bootstrap Muse-UI UI

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of This article will give you an in-depth understanding of Angular11. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete