data绑定overview
Angular providing了 many 种data绑定方式, 用于 in componentclass and 模板之间建立联系.
提示
data绑定 is Angular framework corefeatures之一, 它简化了component and 模板之间 通信.
1. 单向绑定
单向绑定 is 指data from component流向模板, or from 模板流向component.
1.1 from component to 模板
// componentclass
export class AppComponent {
title = 'My Angular App';
isLoggedIn = true;
}
// 模板
{{ title }}
欢迎回来!
![examplegraph片]()
1.2 from 模板 to component
// componentclass
export class AppComponent {
onButtonClick(event: MouseEvent) {
console.log('按钮被点击了!', event);
}
}
// 模板
2. 双向绑定
双向绑定 is 指data in component and 模板之间双向流动, Angular using [(ngModel)] 语法implementation.
注意
using [(ngModel)] 需要先import FormsModule module.
// app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
BrowserModule,
FormsModule // import FormsModule
],
// ...
})
export class AppModule { }
// componentclass
export class AppComponent {
username = '';
}
// 模板
你输入 user名 is : {{ username }}
eventprocessing
Angular providing了强 big eventprocessingmechanism, 可以processing各种 DOM event.
1. basiceventprocessing
// componentclass
export class AppComponent {
count = 0;
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
// 模板
{{ count }}
2. eventobject
可以through $event variable获取eventobject:
// componentclass
export class AppComponent {
onKeyDown(event: KeyboardEvent) {
console.log('按键按 under : ', event.key);
}
}
// 模板
3. event修饰符
Angular providing了event修饰符, 用于简化eventprocessing:
(click.stop): 阻止event冒泡(click.prevent): 阻止默认behavior(click.self): 只 has 当event目标 is 元素本身时才触发(click.once): event只触发一次
阻止默认behavior
模板variable
模板variable用于 in 模板in引用 DOM 元素 or component:
data绑定 best practices
- 优先using单向绑定, 只 in 必要时using双向绑定
- 避免 in 模板in执行 complex 逻辑, 将逻辑放 in componentclassin
- using
ng-containerfor条件渲染, 避免添加不必要 DOM 元素 - for 于 big 型list, 考虑using虚拟滚动optimizationperformance
练习 1: implementation一个 simple 计数器
- creation一个component, package含一个计数器variable
- implementation加, 减, resetfunctions 按钮
- using双向绑定显示当 before 计数
- 添加一个输入框, 可以直接设置计数值
练习 2: implementation一个 simple 表单
- creation一个package含姓名, 邮箱 and password字段 表单
- using双向绑定绑定表单字段
- 添加表单submittingeventprocessing
- in 控制台打印表单data