一、app.module.ts中配置

  1. import {FormsModule} from '@angular/forms'

image.png

二、在组件中使用

header.component.html中

  1. <input type="text" [(ngModel)]="msg">
  2. <p>{{msg}}</p>

三、(change)、(ngModelChange)

change

  1. <input type="text"
  2. (change)="handleChange($event)"
  3. [(ngModel)]="msg">
  1. handleChange(e){
  2. console.log(e.target)
  3. }

onModelChange

  • 只要ngModel依赖的值改变的时候,就会触发
    1. <input type="text"
    2. [(ngModel)]="msg"
    3. (ngModelChange)="handleChange()"
    4. >
    5. <p>{{msg}}</p>
  1. <input type="checkbox"
  2. [(ngModel)]="checked"
  3. (ngModelChange)="inputChange()"
  4. >

四、checkbox中的双向绑定

Tip:此处有坑!
ngModel和ngModelChange顺序不能错

  1. <input type="checkbox" [(ngModel)]="checked" (ngModelChange)="handleChange()">
  1. export class HeaderComponent implements OnInit {
  2. public checked:boolean = true
  3. constructor() { }
  4. ngOnInit() {
  5. }
  6. handleChange(){
  7. console.log(this.checked)
  8. }
  9. }