有一篇讲的非常透彻:

https://oomusou.io/angular/ngmodel/

以下是应用举例:

在component.ts中,双向绑定的字段这么写:

1
2
3
4
5
6
7
  @Input() topicSelection: string;
  @Output() topicSelectionChange = new EventEmitter();

  public change()
  {
    this.topicSelectionChange.emit(this.topicSelection);
  }

在html中:

1
  <ion-radio-group [(ngModel)]="topicSelection" (ngModelChange)="change()">

在调用component的html中

1
<customer-topic [topic]="topic" [(topicSelection)]="topicSelection"></customer-topic>
  • 使用ngModel directive 需要使用 FormsModule, 需要import FormsModule
  • [()]学名叫 Banana in a Box 语法使用双向绑定;

第二种写法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  _topicSelection: string;
  @Output() topicSelectionChange = new EventEmitter();
  @Input()
  get topicSelection() {
    return this._topicSelection;
  }
  set topicSelection(val) {
    this._topicSelection = val;
    this.topicSelectionChange.emit(this._topicSelection);
  }

更清晰一些!