由於考量有許多欄位需要新增,決定在主頁設計一個button
按下去就可以換頁,在新的頁面進行新增資料
增加一個trievent-add
component,並設定好rouete
{path: 'trievent-Add', component: TrieventAddComponent}
運用route的特性撰寫換頁的function
addTriData() {
this._router.navigate(['/trievent-Add'], {
queryParams: {
// pParams: data.name //跟dialogu一樣可以帶參數
}
});
}
設計新增的一筆競賽的畫面
建一個跟後端資料庫一樣型別的
newTridata
來綁定新增的ngModel各屬性值
需要回前頁與key完新資料後的button
<button mat-fab color="primary" (click)="goBack()">
<span matTooltip="回前頁">
<mat-icon>reply</mat-icon>
</span>
</button>
<button mat-fab color="accent" (click)="createTriData(newTridata)">
<span matTooltip="確認新增">
<mat-icon>file_download</mat-icon>
</span>
</button>
依據資料庫欄位建立一個空白表單,運用input
與下拉式選單來登打
//input輸入值
<mat-form-field class="standard-width">
<input matInput [(ngModel)]="newTridata.name" placeholder="比賽名稱">
</mat-form-field>
//直接給下拉式選項值
<mat-form-field class="standard-width">
<mat-select [(ngModel)]="newTridata.year" placeholder="年">
<mat-option value="2018"> 2018</mat-option>
<mat-option value="2019"> 2019</mat-option>
<mat-option value="2020"> 2020</mat-option>
</mat-select>
</mat-form-field>
//利用ngFor撈值給下拉式選項值
<mat-form-field class="standard-width">
<mat-select placeholder="月" [(ngModel)]="newTridata.month">
<mat-option>-</mat-option>
<mat-option *ngFor="let i of months" [value]="i.CODE">
{{i.NAME}}
</mat-option>
</mat-select>
</mat-form-field>
由於我們的資料欄位型別裡面有一個Array<Event>
,一對多的關係
這邊需要運用*ngFor
與陣列的操作來處理
先new一個newEvent
public newEvent: EVENT = new EVENT();
<mat-card>
<mat-form-field class="standard-width">
<input matInput [(ngModel)]='newEvent.eventgroup' placeholder="組別">
</mat-form-field>
<mat-form-field class="standard-width">
<input matInput [(ngModel)]='newEvent.name' placeholder="競賽名稱">
</mat-form-field>
//......
<button mat-fab color="primary" (click)="addEvent2TriData(newEvent)">
<span matTooltip="增加一筆競賽組別">
<mat-icon>add</mat-icon>
</span>
</button>
</mat-card>
使用readonly
讓input不能再改
<h3>競賽組別</h3>
<div>
<mat-card *ngFor="let i of newTridata.tri_event" class="card-added">
<mat-form-field class="standard-width">
<input matInput [(ngModel)]='i.eventgroup' placeholder="組別" readonly>
</mat-form-field>
<mat-form-field class="standard-width">
<input matInput [(ngModel)]='i.name' placeholder="競賽名稱" readonly>
</mat-form-field>
//.................
</mat-card>
</div>
//回前頁
goBack() {
this.location.back();
}
//新增一筆競賽資料
createTriData(item: Triathlon) {
this.programService.postBackendData(item).subscribe(
(response: any) => {
this.shareDialogService.openShareDialog(response.data.name + '新增成功');
},
(error: HttpErrorResponse) => this.programService.HandleError(error)
);
}
將競賽組別資料塞入競賽主檔,關鍵一刻
public newEvent: EVENT = new EVENT();
public Events: Array<EVENT> = new Array<EVENT>() //用來接多筆競賽組別資料
//........
addEvent2TriData(item: EVENT) {
this.Events.push(item); //將多筆競賽組別資料放進去
this.newTridata.tri_event = this.Events; //給主檔
this.newEvent = new EVENT();//將前端綁定model清空以利下一筆資料新增
}