本文介绍了Angular2:父/子组件内部的双向绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

版本:"angular2":"2.0.0-beta.6"

Version: "angular2": "2.0.0-beta.6"

我想在父/子组件案例中实现双向绑定.

I would like to implement a two way binding inside a parent/child component case.

在子组件上,我使用双向绑定在编辑时显示文本.

On my child component, I'm using two-way binding to display text while editing.

子组件(InputTestComponent [selector:'input-test']):

<form (ngSubmit)="onSubmit()" #testform="ngForm">
    {{name}}
    <textarea #textarea [(ngModel)]="name" ngControl="name" name="name"></textarea>
    <button type="submit">Go</button>
</form>

然后,我想将此更改传播到他的父组件.我尝试使用[(name)]="name"失败了.

Then, I would like to propagate this change to his parent component.I tried with [(name)]="name" with no success.

父组件:

<div>
  {{name}}
  <input-test [(name)]="name"></input-test>
</div>

代码示例

最简单的方法(不太冗长)是什么?

What the easiest way to do it (less verbose) ?

推荐答案

对于2向绑定,请使用@Input()@Output().名称应为propNamepropNameChange,以允许使用速记绑定语法[(propName)]="someModel",否则,您将需要较长版本的[propName]="someModel" (propNameOtherOutputName)="propName=$event;propNameOtherOutputName.emit($event)"

For 2-way binding use @Input() and @Output(). The names should be propName and propNameChange to allow the shorthand binding syntax [(propName)]="someModel" otherwise you'd need the longer version [propName]="someModel" (propNameOtherOutputName)="propName=$event;propNameOtherOutputName.emit($event)"

@Component{
  ...
  template: `
<textarea #textarea [(ngModel)]="name" (ngModelChange)="nameChange.emit($event)" ngControl="name" name="name"></textarea>

`})
export class InputTestComponent {
  @Output() nameChange:EventEmitter<String> = new EventEmitter<String>();
  @Input() name:string;
}

这篇关于Angular2:父/子组件内部的双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:50