学习angular6,漫长并充实的过程,今日发现一个问题
数组['aaa','bbb','ccc']遍历后,每个项都和input进行双向绑定,为什么改变input值,这个数组 里面的项(值变量)不改变;如果是[{a:'aaa'},{b:'bbb'},{c:'ccc'}],这样的项(引用型变量) 遍历后每个项进行双向绑定就可以实现表单改变项的值,数组也改变
办法总比困难多!
搜索资料和文献发现
方法1
[(ngModel)]="item[index]
方法1确实能够解决绑定的问题,但是又发现另外一个问题,每次表单修改项的时候,表单只=值一旦改变,表单就丢失了焦点,很不友好,探索发现方法2
方法2
*ngFor="let value of values; trackBy:indexTracker" indexTracker(index: number, value: any) { return index; }
这种自定义trackBy的方式才是正确的路子,既保证了项的绑定,也能避免数组持续的从头遍历刷新,完美解决!