Angular2 select用法-設定預設值和事件

來源:互聯網
上載者:User

設定預設值:
現在有三個學生小明,小紅,小黑,對雙向繫結的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的知識

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.