ngModel的更新值未反映在组件

时间:2018-06-06 06:33:35

标签: angular angular5 angular-ngmodel

我有一个ControlValueAccessor实现的组件,但是当绑定值在组件外部更改时,它无法正确更新。

修改
Stackblitz示例: https://stackblitz.com/edit/angular-lmojnj

我将解释一下这个 一开始,阵列中有两个图像,如果我点击其中一个图像,它将触发toggleSelected图像分类器,它将更新tempImages只有1个图像(未点击的图像)。
然后,如果我在parent.component的输入中放入一个图像的url并单击enter,它将触发parent.component的addImage,它将url推送到tempImages,因此应该在images-sorter(应该自动调用writeValue导致值改变? - 并且它不会)。 现在,如果我点击我之前点击的相同图像(或者选中的其他图像),我之前添加的新图像会出现! 它应该在我将其添加到tempImages数组时出现,因为它是双向绑定,不是吗?

为了解决这个问题,我添加了对图像分类器的引用(<app-images-sorter2 #imagesSorter [(ngModel)]="tempImages"></app-images-sorter2>) 然后将引用传递给addImage并调用imageSorterCompoennt.writeValue(this.tempImages);来更新我期望的内容,但据我所知,这是一种不好的做法和错误的解决方案

图像-sorter2.component.ts:

import { Component, forwardRef, ViewEncapsulation } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Component({
  selector: 'app-images-sorter2',
  templateUrl: './images-sorter2.component.html',
  styleUrls: ['./images-sorter2.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ImagesSorter2Component),
      multi: true
    }
  ],
  encapsulation: ViewEncapsulation.None
})
export class ImagesSorter2Component implements ControlValueAccessor {
  public allImages: string[] = [];
  public images: string[] = [];

  private onChange: (_: any) => void = () => {};

  constructor() {}

  public writeValue(value: string[]): void {
    this.images = value || [];
    this.images.forEach((image) => {
      if (!this.allImages.includes(image)) {
        this.allImages.push(image);
      }
    });
    this.onChange(this.images);
  }

  public registerOnChange(fn: (_: any) => void): void {
    this.onChange = fn;
  }

  public registerOnTouched(): void {}

  public isSelected(image: string): boolean {
    return this.images.includes(image);
  }

  public getImageModelIndex(image: string): number {
    return this.images.indexOf(image);
  }

  public toggleSelected(image: string): void {
    const indexOfImage = this.getImageModelIndex(image);
    let newValue;
    if (indexOfImage > -1) {
      newValue = [...this.images.slice(0, indexOfImage), ...this.images.slice(indexOfImage + 1)];
    } else {
      newValue = [...this.images, image];
    }
    this.writeValue(newValue);
  }
}

图像-sorter2.component.html:

<div fxLayout="row wrap">
  <div *ngFor="let image of allImages"
       class="image-wrapper"
       [ngClass]="{'selected': isSelected(image)}"
       (click)="toggleSelected(image)">
    <div class="index-container">
      <div>{{ getImageModelIndex(image)+1 }}</div>
    </div>
    <div class="image-container">
      <img [src]="image" />
    </div>
  </div>
</div>

parent.component.ts:

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ParentComponent {
  public tempImages = [
    'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Google_Chrome_icon_%28September_2014%29.svg/1200px-Google_Chrome_icon_%28September_2014%29.svg.png',
    'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/1200px-Apple_logo_black.svg.png'
  ];
  public newImage: string = '';

  public addImage(): void {
    this.tempImages.push(this.newImage);
    this.newImage = '';
  }
}

parent.component.html:

<app-images-sorter2 [(ngModel)]="tempImages"></app-images-sorter2>
  <div>
    <mat-form-field>
      <input matInput
             type="text"
             [(ngModel)]="newImage"
             (keyup.enter)="addImage()"
             placeholder="Image URL">
    </mat-form-field>
  </div>

2 个答案:

答案 0 :(得分:1)

之前我遇到过此问题,似乎ControlValueAccesor在注意集合更改方面存在问题,因此您必须重新分配数组。

为您的示例更改来自

的parent.ts文件中的第18行
this.tempImages.push(this.newImage);

this.tempImages = this.tempImages.concat([this.newImage]);

它应该可以正常工作。

答案 1 :(得分:0)

stckblitz显示includes上没有string[]函数。

根据docs它应该有效,但在将其替换为.indexOf(image) === -1之后,它可以正常工作。 Example