Cannot assign to a reference or variable (ngModel with custom component)

Sil*_*ito 2 components angular

I am trying to set the ngModel from my custom component, but I am receiving an error message. I need to add the support to Two Way DataBind on this component.

I tried to use this tutorial:

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

The loop code (The collection.bookmark is an empty array in this test)

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

The code of component

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

Syn*_*ose 7

您不能在控制器外部的变量上使用 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>
Run Code Online (Sandbox Code Playgroud)