Angular雙向數據綁定


一,引入模塊

import {FormsModule} from "@angular/forms";

二,js中定義綁定數據

public user:any={
    username:'',
    sex:'1',
    cityList:['北京','上海','深圳'],
    city:'北京',

    hobby:[
      {
        title:'吃飯',
        checked:false
      },
      {
        title:'睡覺',
        checked:false
      },
      {
        title:'敲代碼',
        checked:false
      }
    ],
    text:''
  }

三,html頁面綁定

<ul>
  <li>
    <input type="text" [(ngModel)]="user.username">
  </li>
  <li>
    <input type="radio" [(ngModel)]="user.sex" value="1"><input type="radio" [(ngModel)]="user.sex" value="2"></li>
  <li>
    <select name="city" id="city" [(ngModel)]="user.city">

      <option *ngFor="let city of user.cityList" [value]="city">{{city}}</option>
    </select>
  </li>
  <li>
    <span *ngFor="let hobby of user.hobby">
      <input type="checkbox" [(ngModel)]="hobby.checked">{{hobby.title}}
    </span>
  </li>

  <li>
    <textarea name="" id="" cols="30" rows="10" [(ngModel)]="user.text"></textarea>
  </li>

  <button (click)="getUser()">獲取user</button>

  {{user | json}}

</ul>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM