子组件中的角度双向数据绑定 [英] Angular two way data binding in child component

查看:38
本文介绍了子组件中的角度双向数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用框内的sytax香蕉进行两种方式的数据绑定,我需要将值向下传递到组件(组件),然后传递到将要对其进行编辑的另一个组件(组件2).

我期望绑定将使更改能够反映在app.component中.但是,我无法执行此操作.

我使用了

compone.component.html已从更改:

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

对此:

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

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.

解决方案

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:

Edited:

compone.component.html is altered from :

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

to this:

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

这篇关于子组件中的角度双向数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆