在我正在编写的 Angular 2 应用程序中,我有一个 select
元素,它通过 [(ngModel)]
绑定(bind)到 Controller 中的一个字段:
<select [(ngModel)]="dateInfo.year" class="form-control">
<option *ngFor="let year of getYearList()" [value]="year">{{year}}</option>
</select>
dateInfo
是 Controller 中的一个属性,它引用包含在名为 DateService
的服务中的 DateInfo
对象:
@Injectable()
export class DateService {
public dateInfo: DateInfo = {
year: 2016
}
}
DateInfo
对象本身是一个简单的 Typescript 接口(interface),只存储年份:
export interface DateInfo {
year: number
}
我使用此接口(interface)的原因是根据 the first answer to this question 将对 year
的更改传播到使用 DateService
的所有组件.
出于某种原因,当从 select
元素更改模型时,整个应用程序会卡住(在 Chrome 和 Edge 中测试)。我做了一个plunker来说明问题here .
提前致谢!
最佳答案
问题是由 getYearList()
为每次调用返回一个新的数组实例引起的。每次运行 Angulars 变更检测时,它都会检测到变更,因为它每次都会获得一个新数组。
我想知道为什么你没有得到“自上次检查以来表达发生了变化”
缓存结果修复了问题 http://plnkr.co/edit/UKA35jIa9v6jFfrbJJuz?p=preview
这就是为什么从模板调用方法通常是不好的做法。而是将方法调用的结果分配给属性并绑定(bind)到该属性。
关于typescript - Angular 2 : Application freezing when model is changed from select input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38753231/