不确定如何在 Angular 上为自定义组件应用双向绑定 [英] Unsure how to apply two-way binding on Angular for a custom component

查看:19
本文介绍了不确定如何在 Angular 上为自定义组件应用双向绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图组件,它从服务中获取数据模型并将其设置为自身的属性.然后,一组自定义组件接收属性的字段作为输入以在其中显示.这按预期工作.

I have a view component that fetches the data model from a service and sets it as a property on itself. Then, a set of custom components recieve the fields of the property as input to display within them. This works as expected.

<app-textbox [caption]="'First name'"
             [value]="data.name.first"></app-textbox>

ngOnInit() {
  this.service.getData()
    .subscribe(res => this.data = res);
}

当自定义组件编辑其内容时,我注意到原始模型没有更新.经过一番谷歌搜索后,我发现我需要以两种方式绑定它并尝试了以下方法(香蕉盒符号显然被称为).遗憾的是,似乎没有任何效果,新条目并没有改变原始模型.

When the custom component gets its contents edited, I noticed that the original model isn't updated. After some googling I found that I need to bind it two-way and tried the following (banana-box notation it's called apparently). Regrettably, it sems not to have any effect and the original model isn't changed with the new entry.

<app-textbox [caption]="'First name'"
             [(value)]="data.name.first"></app-textbox>

我也尝试应用 ngModel 如下所示,但这导致错误消息说没有未指定名称属性的表单控件的值访问器.检查 docs 给了我一个想法,它应该可以工作,但没有我需要的那么详细.

I also tried to apply ngModel as shown below but that led to error message saying that No value accessor for form control with unspecified name attribute. Checking the docs gives me an idea hwo it's supposed to work but not quite as detailed as I need.

<app-textbox [caption]="'First name'"
             [(ngModel)]="data.name.first"></app-textbox>

我需要一个指向我哪里出错的指针.我需要在自定义组件的某个地方发出值吗?我必须使用表格吗?我现在解决它的唯一想法是标记所有控件并手动收集值.这显然是一种不好的做法.

I need a pointer to where I'm going wrong. Is it somewhere in the custom component that I need to emit out the value? Do I have to use a form? The only idea to resolve it I have now is to label all the controls and collect the values manually. That's obviously a bad practice.

推荐答案

是的,您是对的,您需要从子组件发出事件,并且需要为事件名称添加后缀Change".在你的情况下应该是

yes you are right you need to emit event from child component and you need to add suffix "Change" to name of your event. In your case it should be

@Output() valueChange = new EventEmitter<string>();

只有这样 angular 才会识别 [()] 语法.

only then angular will recognize [()] syntax.

这篇关于不确定如何在 Angular 上为自定义组件应用双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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