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

时间:2018-07-26 16:07:33

标签: angular components

我正在尝试从自定义组件中设置ngModel,但收到一条错误消息。我需要在该组件上为双向WayBind添加支持。

我尝试使用本教程:

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

1 个答案:

答案 0 :(得分:3)

您不能在控制器外部的变量上使用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>