<form> <input type="text" class="txt" name="mygoal" placeholder="生活目标.." [(ngModel)]="mygoal"> <br/> {{mygoal}} <input type="submit" class="btn" value="添加目标" (click)='add()'> </form>如果不在app.module.ts中添加
import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule FormsModule ], providers: [], bootstrap: [AppComponent] })
会报错Error:Template parse eeror
Can't bind to 'ngModle' since it isn't a known property of 'input'
学习表单时候遇到的
2.在Angular中利用trackBy来提升性能是如何实现的
在Angular的模板中遍历一个集合(collection)的时候你会这样写:
<ul> <li *ngFor="let item of collection">{{item.id}}</li> </ul>
有时你会需要改变这个集合,比如从后端接口返回了新的数据。那么问题来了,Angular不知道怎么跟踪这个集合里面的项,不知道哪些该添加哪些该修改哪些该删除。结果就是,Angular会把该集合里的项全部移除然后重新添加。
这样做的弊端是会进行大量的DOM操作,而DOM操作是非常消耗性能的。
那么解决方案是,为*ngFor添加一个trackBy函数,告诉Angular该怎么跟踪集合的各项。trackBy函数需要两个参数,第一个是当前项的index,第二个是当前项,并返回一个唯一的标识
@Component({ selector: 'my-app', template: ` <ul> <li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li> </ul> <button (click)="getItems()">Refresh items</button> `, }) export class App { constructor() { this.collection = [{id: 1}, {id: 2}, {id: 3}]; } getItems() { this.collection = this.getItemsFromServer(); } getItemsFromServer() { return [{id: 1}, {id: 2}, {id: 3}, {id: 4}]; } trackByFn(index, item) { return index; // or item.id } }
这样做之后,Angular就知道哪些项变动了
我们可以看到,DOM只重绘了修改和增加的项。而且,再次点击按钮是不会重绘的。但是在没有添加trackBy函数的时候,重复点击按钮还是会触发重绘的