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

查看:89
本文介绍了不确定如何对自定义组件在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 ,但这导致错误消息指出没有用于未指定名称属性的表单控件的值访问器.检查文档给了我一个想法,它应该可以工作,但是没有我需要的那么详细

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天全站免登陆