angular 学习碰到的一些坑

        <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]
})
@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函数的时候,重复点击按钮还是会触发重绘的

 

 

 

遇到以下的问题: 

ERROR Error: Uncaught (in promise): TypeError: __webpack_require__.e is not a function

解决方法:

npm remove -g @angular/cli
npm install -g @angular/cli@1.7.4
npm remove @angular/cli
npm add @angular/cli@1.7.4 --save-dev

其中1.7.4可以替换成其他版本,但是要大于等于之前安装的angular/cli版本

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值