无法分配给引用或变量(具有自定义组件的ngModel)



我正试图从自定义组件设置ngModel,但收到一条错误消息。我需要在这个组件上添加对双向数据绑定的支持。

我试着使用这个教程:

https://thiagomelin.com.br/2017/08/09/angular-2-criando-um-custom-component-com-ngmodel/

循环代码(collection.bookmark在此测试中是一个空数组(

<div *ngFor="let b of collection.bookmark">
<app-telephonist-control [(ngModel)]="b"></app-telephonist-control>
<pre>{{ b | json}}</pre>
</div>

组件的代码

import { Component, OnInit, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

export const resourceValueProvider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TelephonistControlComponent),
multi: true
};
@Component({
selector: 'app-telephonist-control',
templateUrl: './telephonist-control.component.html',
styleUrls: ['./telephonist-control.component.scss'],
providers: [resourceValueProvider]
})
export class TelephonistControlComponent implements OnInit, ControlValueAccessor {
private resourceValue: any;
private changed = new Array<(value: any) => void>();
private touched = new Array<() => void>();
constructor() { }
ngOnInit() {
}
get value(): any {
return this.resourceValue;
}
set value(value: any) {
if (this.resourceValue !== value) {
this.resourceValue = value;
this.changed.forEach(f => f(value));
}
}
touch() {
this.touched.forEach(f => f());
}

writeValue(value: any) {
this.resourceValue = value;
}

registerOnChange(fn: (value: any) => void) {
this.changed.push(fn);
}
registerOnTouched(fn: () => void) {
this.touched.push(fn);
}
}

您不能在控制器之外的变量上使用ngModel,在本例中,控制器是由for循环创建的临时变量。为了正确绑定ngModel,在一个范围内迭代并使用索引来获取要绑定的对象:

<div *ngFor="let b of collection.bookmark;let index = index">
<app-telephonist-control [(ngModel)]="collection.bookmark[index]"></app-telephonist-control>
<pre>{{ b | json}}</pre>
</div>

最新更新