設定預設值:
現在有三個學生小明,小紅,小黑,對雙向繫結的student設定你想要的select值就可以在下拉框預設選中
code1:
設定”請選擇”為預設項,只需要把變數student設定為‘’,即可預設到“請選擇”
方案1:
TS:students:string[]=['xiaoming','xiaohong','xiaohei'];student:string='';HTML: <select [(ngModel)]="student"> <option value="">請選擇</option> //此處用的是value,而不是[value] <option *ngFor="let item of students" [value]='item'>{{item}}</option> </select>
方案2:
TS:students:string[]=['','xiaoming','xiaohong','xiaohei'];student:string='';HTML:<select [(ngModel)]="student"> <option *ngFor="let item of students" [value]='item'>{{item || '請選擇'}}</option> </select>
code2:
當需要設定預設值到xiaoming時,只需要將變數student的初始值設為“xiaoming”
TS:students:string[]=['xiaoming','xiaohong','xiaohei'];student:string='xiaoming';HTML: <select [(ngModel)]="student"> <option *ngFor="let item of students" [value]='item'>{{item}}</option> </select>
綁定事件
select下拉框主要通過ngModel和ngModelChange實現選擇事件
如果你想要在select下拉框選中某一項時觸發事件,可以將[(ngModel)]拆成ngModel和ngModelChange來實現
TS:students:string[]=['xiaoming','xiaohong','xiaohei'];student:string='';info:string='';setInfo(){ this.info=student;}HTML:<select [ngModel]="student" (ngModelChange)="student=$event;setInfo()"> <option value="">請選擇</option> <option *ngFor="let item of students" [value]='item'>{{item}}</option> </select>{{info}}
在屬性綁定中,一個值從模型中傳到螢幕上的目標屬性。 我們通過把名字括在方括弧中來標記出目標屬性, [] 。 這是一個 從模型到視圖 的單向資料繫結。
在事件綁定中,值從螢幕上的目標屬性傳到模型中。 我們通過把名字括在圓括弧中來標記出目標屬性, () 。 這是一個 從視圖到模型 的反向單向資料繫結。
在Angular2中[(x)] 的繫結目標時,會以x和xChange表示他的輸入和輸出屬性。
代碼中student=$event 原理如下ngModelChange是一個 Angular EventEmitter 類型的屬性,當它觸發時,它返回的是輸入框的值
點擊觀看更多關於ngModel的知識