user3836415
user3836415

Reputation: 982

Angular two way data binding in child component

I'm trying to do two way databinding using the banana in box sytax, and I need to pass a value down to a component (compone) then to another component (comptwo) where it will be edited.

My expectation was that the binding will enable the changes to be reflected in the app.component. However, I'm unable to do this.

I've used the example from this stackoverflow response, although it is not the voted answer to the question. I've seen this being represented in other blogs.

I've created a stackblitz of my issue. I'm just after help and possible explanation of what I'm doing wrong ?

Edited : to include code snippets from stackblitz:

App.Component.ts

export class AppComponent  {
  public _Name = 'Angular';  
}

app.component.html

From app.component.html : {{_Name}}

compone.component.ts

...
public _Name:string = "";
@Output() NameChange:EventEmitter<string> = new EventEmitter<string>();
@Input()
set Name(value:string)
{

  this._Name = value;
  this.NameChange.emit(value);

}
get Name():string
{
  return this._Name;

}
...

compone.component.html

...
<p>
compone works!
<app-comptwo [(Name)]="_Name"></app-comptwo>
{{_Name}}
</p>
...

comptwo.component.ts

...
public _Name:string = "";
@Output() NameChange:EventEmitter<string> = new EventEmitter<string>();
@Input()
set Name(value:string)
{

  this._Name = value;
  this.NameChange.emit(value);

}
get Name():string
{
  return this._Name;

}
...

comptwo.component.html

...
<p>
comptwo works! <input [(ngModel)]="_Name">
{{_Name}}
</p>
...

As it can be seen above, app.component is where the field originates from. It is passed into compone, and then into comptwo. Comptwo component is where the field is being modified via an input tag.

Upvotes: 0

Views: 503

Answers (1)

Antoniossss
Antoniossss

Reputation: 32507

If you are using setter/getter, you have to bind events to them (in this case Name, not directly to model field (_Name). Getters/setters wont be called otherwise if you are binding to private _Field as you are literally bypassing setters.

https://stackblitz.com/edit/angular-awlpfh

Result of using propert bindings:

enter image description here

Edited:

compone.component.html is altered from :

<app-comptwo [(Name)]="_Name"></app-comptwo>

to this:

<app-comptwo [(Name)]="Name"></app-comptwo>

Upvotes: 2

Related Questions