Unsure how to apply two-way binding on Angular for a custom component

纵然是瞬间 提交于 2020-01-06 05:50:07

问题


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>

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.


回答1:


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>();

only then angular will recognize [()] syntax.




回答2:


Your component either has to be a form control and implement ControlValueAccessor. You can read more about it for example here https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html. That's in the case if your component does some "input-ish" stuff (type and display text).

Or you should add an @Input() and an @Output() to your component and handle it in the way you need. In that case your binding will be split and the template would look something like this <app-textbox [caption]="'First name'" (change)="handleChange($event)"></app-textbox>. In this example the @Input() is caption and the @Output() is change.



来源:https://stackoverflow.com/questions/57547337/unsure-how-to-apply-two-way-binding-on-angular-for-a-custom-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!