Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

angular - Angular2 : two way binding inside parent/child component

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.

Child component (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>

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

Parent component:

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

Code sample

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...