Angular雙向綁定簡單理解

在使用Antd的時候,一直很好奇裏面的雙向綁定的自定義組件是怎麼做的。

因爲之前一直用,沒有去細看文檔。

今天抽空來簡單的擼一下。

在ng中,()是單向數據流,從視圖目標到數據源,[()]這樣就是雙向綁定了。簡單的說就是ng給的一個語法糖,幫我們做了子組件內部事件發射的事件監聽,然後賦值。

子組件:html

<input placeholder="test" type="text" [(ngModel)]="qc" #qq (ngModelChange)="testevent()">

子組件:ts

@Component({
  selector: 'app-qingcheng',
  templateUrl: './qingcheng.component.html',
  styleUrls: ['./qingcheng.component.less']
})
export class QingchengComponent implements OnInit {

  @Input() username: string;
  @Output() usernameChange = new EventEmitter();

  constructor() { }

  ngOnInit() {

  }
  testevent() {
    console.log(this.username);
    this.usernameChange.emit(this.username);
  }

}    

向外部發射事件的時候,一定要xxxChange,以Change結尾的事件才正確,不然無法雙向綁定。。

這個坑找了半天才解決:https://segmentfault.com/a/1190000016651999

父組件:html

<app-qingcheng #qingcheng  [(qc)]="testbind"></app-qingcheng>
{{testbind}}

父組件:ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  title = 'qctest';
  testbind = '';

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章