子组件中的角度双向数据绑定

时间:2019-03-27 14:07:56

标签: angular

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

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

我使用了此stackoverflow响应中的示例,尽管它不是对该问题的投票答案。我已经在其他博客中看到了这一点。

我已经为问题创建了stackblitz。我只是在寻求帮助并且可能对自己做错的事情进行了解释?

已编辑:,以包含来自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>
...

从上面可以看到,app.component是字段的来源。它被传递到compone,然后传递到comptwo。 Comptwo组件是通过输入标签修改字段的地方。

1 个答案:

答案 0 :(得分:3)

如果使用的是setter / getter,则必须将事件绑定到它们(在这种情况下为Name,而不是直接绑定到模型字段(_Name)。如果您使用getter / setter,则不会调用该方法正实际上绕过设置器,因此绑定到专用_Field

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

使用属性绑定的结果:

enter image description here

已编辑:

compone.component.html已从更改:

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

对此:

<app-comptwo [(Name)]="Name"></app-comptwo>
相关问题