Figure 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>apply
Notify 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 '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@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
|
|
|
#Two-way binding Several forms | Attribute binding and event binding | Template 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: 'root',
})
特定注册
@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
git clone https://github.com/angular/quickstart.git my-app
cd ./my-app
npm run install
npm start
五、对比VUE
5.1 技术对比
主要点 |
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 |
更多编程相关知识,请访问:编程视频!!