Angular雙向綁定簡單理解

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

由於以前一直用,沒有去細看文檔。segmentfault

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

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

子組件:htmlthis

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

子組件:tsspa

@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結尾的事件才正確,否則沒法雙向綁定。。雙向綁定

這個坑找了半天才解決:http://www.javashuo.com/article/p-dllxmkdi-cz.htmlcode

父組件:htmlcomponent

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

父組件:tshtm

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

}
相關文章
相關標籤/搜索