今天的內容是昨天的延伸,但跟ngModel果然不熟,整個晚上都在找ngModel套到ngFor的方法,後來才發現是要儲存的變數代錯……睡眠不足果然不利思考orz
最終找到的解法:
<input type="number" class="form-control" [id]="i.status" [name]="i.status" [value]="i.value" [(ngModel)]="i.value">
其實一開始就在網路上找到答案了,但這裡的input type是number,最初傻傻的跟著範例用跟id一樣的值放進 [(ngModel)],但id是string,所以input內理所當然跑不出對應的值(小murmur一下……既然該放number的地方被放進了string,就不能console報錯一下嗎害我找bug找半天= =)
整個html的部分:
<div *ngFor="let i of items;let index = index;" class="col-4 mb-2 d-flex">
<!-- <statusItem [item]="i" class=""></statusItem> -->
<label class="mr-2">{{ i.status | uppercase}}</label>
<input type="number" class="form-control" [id]="i.status" [name]="i.status" [value]="i.value" [(ngModel)]="i.value">
</div>
<button type="button" class="btn btn-primary mr-2" (click)="saveStatusItem()">Save</button>
<button type="button" class="btn btn-primary" (click)="getProfileData()">Load</button>
Ts寫法與Profile的部分雷同:
saveStatusItem(f: NgForm): void {
let saveStatusData = {
"statusData": [
this.items[0].value,
this.items[1].value,
this.items[2].value,
this.items[3].value,
this.items[4].value,
this.items[5].value,
this.items[6].value,
this.items[7].value
]
};
localStorage.setItem('statusData', JSON.stringify(saveStatusData));
alert('資料已儲存');
}
getStatusItem() {
let data = JSON.parse(localStorage.getItem('statusData'));
this.items[0].value = data['statusData'][0];
this.items[1].value = data['statusData'][1];
this.items[2].value = data['statusData'][2];
this.items[3].value = data['statusData'][3];
this.items[4].value = data['statusData'][4];
this.items[5].value = data['statusData'][5];
this.items[6].value = data['statusData'][6];
this.items[7].value = data['statusData'][7];
}
之後就是整合整個頁面的Save/Load方式,讓各component內的input能夠統一用一個button控制。
= = = = = = = = = =
你今天的努力,
是否有跟未來的夢想
同一個等級?