設置默認值:
現在有三個學生小明,小紅,小黑,對雙向綁定的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 類型的屬性,當它觸發時,它返回的是輸入框的值