模板语法文档中对此进行了解释使用 NgModel 进行双向绑定 https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngModel部分:
<input [(ngModel)]="currentHero.firstName">
在内部,Angular 映射了该术语,ngModel
, to an ngModel
输入属性和ngModelChange
输出属性。这是它匹配的更通用模式的一个具体示例[(x)]
to an x
属性绑定的输入属性和xChange
事件绑定的输出属性。
如果我们愿意的话,我们可以编写自己的遵循此模式的双向绑定指令/组件。
另请注意[(x)]
只是属性绑定和事件绑定的语法糖:
[x]="someParentProperty" (xChange)="someParentProperty=$event"
在你的情况下,你想要
<my-comp [(inputText)]="testString"></my-comp>
所以你的组件必须有一个inputText
输入属性和inputTextChange
输出属性(这是一个EventEmitter
).
export class MyComp {
@Input() inputText: string;
@Output() inputTextChange: EventEmitter<string> = new EventEmitter();
}
每当您的组件更改值时,通知父级更改inputText
,发出一个事件:
inputTextChange.emit(newValue);
在您的场景中,MyComp 组件绑定输入属性inputText
使用[(x)]
格式为 ngModel,因此您使用了事件绑定(ngModelChange)
收到更改通知,并在该事件处理程序中通知父组件更改。
在其他不使用 ngModel 的场景中,重要的是emit()
每当财产价值发生事件inputText
MyComp 组件中的更改。