為了弄懂ngModule,這邊比預計提前開始實作Save/Load,總之文章就是按照實作順序來寫了。
找資料時發現ngModule應用方法似乎不少,這裡只用了最基本的功能,在input上宣告ngModule並綁定name,在component.ts中就可以讀取到input輸入的值了。
HTML:
<form #form="ngForm" (ngSubmit)="saveFormData(form.value)">
<div class="form-group d-flex my-2">
<label for="chName">Name</label>
<input type="text" class="form-control"
id="chName" name="chName"
[(ngModel)]="chName" placeholder="角色姓名">
</div>
<div class="form-group d-flex my-0">
<label for="plName">Player</label>
<input type="text" class="form-control"
id="plName" name="plName"
[(ngModel)]="plName" placeholder="玩家姓名">
</div>
<div class="d-flex my-0">
<div class="">
<label for="age">Age</label>
<input type="text" class="form-control"
id="age" name="age"
[(ngModel)]="age" placeholder="年齡">
</div>
<div class="">
<label for="gender">Gender</label>
<input type="text" class="form-control"
id="gender" name="gender"
[(ngModel)]="gender" placeholder="性別">
</div>
</div>
<div class="form-group d-flex my-2">
<label for="occupation">Occupation</label>
<input type="text" class="form-control"
id="occupation" name="occupation"
[(ngModel)]="occupation" placeholder="職業">
</div>
<div class="form-group d-flex my-2">
<label for="birthplace">Birthplace</label>
<input type="text" class="form-control"
id="birthplace" name="birthplace"
[(ngModel)]="birthplace" placeholder="出生地">
</div>
<button type="submit" class="btn btn-primary mr-2">Save</button>
<button type="button" class="btn btn-primary"
(click)="getProfileData()">Load</button>
</form>
TS:
export class ProfileComponent {
title = `Profile`;
chName;
plName;
age;
gender;
occupation;
birthplace;
saveFormData(f: NgForm): void {
let profiledata = {
"profiledata": [
this.chName,
this.plName,
this.age,
this.gender,
this.occupation,
this.birthplace
]
};
localStorage.setItem('profiledata', JSON.stringify(profiledata));
alert('資料已儲存');
console.log(profiledata);
}
getProfileData() {
let data = JSON.parse(localStorage.getItem('profiledata'));
this.chName= data['profiledata'][0];
this.plName= data['profiledata'][1];
this.age= data['profiledata'][2];
this.gender= data['profiledata'][3];
this.occupation= data['profiledata'][4];
this.birthplace= data['profiledata'][5];
}
}
實作結果如下:
https://i.imgur.com/70DpFeA.gif
這樣基本Save/Load方法就完成了,目前因為各區塊都是獨立元件,所以Save/Load功能需要再獨立成一個元件,希望能夠達成整個網頁統一使用一個Save與Load按鈕。
另外還有讀取複數角色卡功能……不過這個算是額外加分題,目前先只專注在基本功能了。
= = = = = = = = = =
你今天的努力,
是否有跟未來的夢想
同一個等級?