簡體   English   中英

Angular — ExpressionChangedAfterItHasBeenCheckedError:表達式在檢查后已更改。 (嵌套的FormArray)

[英]Angular — ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. (Nested FormArray)

前言 :我意識到這可能是重復的,但是閱讀了此處錯誤的詳細說明后,我仍然不明白我的代碼將如何使更改檢測中執行的臟檢查無效。

我有一個包含FormArray的FormGroup。 我想將FormArray嵌套到一個子組件中,因為它包含了很多自己的特定業務邏輯。

在瀏覽器中加載組件時,以及在運行單元測試時,會收到以下異常:

ParentComponentA.html:2 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.
    at viewDebugError (core.es5.js:8426)
    at expressionChangedAfterItHasBeenCheckedError (core.es5.js:8404)
    at checkBindingNoChanges (core.es5.js:8568)
    at checkNoChangesNodeInline (core.es5.js:12448)
    at checkNoChangesNode (core.es5.js:12414)
    at debugCheckNoChangesNode (core.es5.js:13191)
    at debugCheckRenderNodeFn (core.es5.js:13131)
    at Object.eval [as updateRenderer] (ParentComponentA.html:2)
    at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13113)
    at checkNoChangesView (core.es5.js:1223

父組件A:

@Component({
  selector: 'app-parent-component-a',
  templateUrl: './parent-component-a.component.html',
  styleUrls: ['./parent-component-a.component.scss']
})
export class ParentComponentA implements OnInit, OnDestroy {
  activeMediaViewport: string; // Should match a value of MaterialMediaQueries enum
  mediaWatcher: Subscription;
  parentForm: FormGroup;
  childComponentDisplayMode: number; // Should match a value of ComponentDisplayModes enum

  constructor(private formBuilder: FormBuilder, private mediaQueryService: ObservableMedia) {
    const prepareComponentBFormControl = (): FormGroup => {
      return formBuilder.group({
        'code': '',
        'weight': '',
        'length': '',
        'width': '',
        'height': '',
      });
    };

    const prepareParentForm = (): FormGroup => {
      return formBuilder.group({
        // ... omitted other properties
        'childComponentList': formBuilder.array([prepareComponentBFormControl()])
      });
    };

  }

  ngOnInit() {
    this.initializeWatchers();
  }

  ngOnDestroy() {
    this.mediaWatcher.unsubscribe();
  }

  /**
   * Sets intervals and watchers that span the entire lifecycle of the component and captures their results to be used for deregistration.
   */
  private initializeWatchers(): void {
    this.mediaWatcher = this.mediaQueryService
      .subscribe(mediaChange => {
        this.activeMediaViewport = mediaChange.mqAlias;
        this.childComponentDisplayMode = this.calculateComponentDisplayMode(this.activeMediaViewport);
      });
  }
}

組件HTML標記屬性

<child-component-b [displayMode]="childComponentDisplayMode"
                   [nestedFormList]="childComponentList">
</child-component-b>

子組件B:

@Component({
  selector: 'child-component-b',
  templateUrl: './child-component-b.component.html',
  styleUrls: ['./child-component-b.component.scss'],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponentB implements OnInit {

  @Input() displayMode: number; // Should match a value of ComponentDisplayModes enum
  @Input() nestedFormList: FormArray;

  mobileDisplays: Array<number>;
  largeDisplays: Array<number>;
  numberOfRowsToAdd: FormControl;

  constructor(private formBuilder: FormBuilder) {
    this.mobileDisplays = [ComponentDisplayModes.TABLET_PORTRAIT, ComponentDisplayModes.PHONE_LANDSCAPE, ComponentDisplayModes.PHONE_PORTRAIT];
    this.largeDisplays = [ComponentDisplayModes.DESKTOP, ComponentDisplayModes.TABLET_LANDSCAPE];
  }

  ngOnInit() {
    // including in this SO post since it references the @Input property
    this.numberOfRowsToAdd = new FormControl(this.defaultRowsToAdd, this.addBuisnessLogicValidator(this.nestedFormList)); 
  }

  private addBuisnessLogicValidator(nestedFormListRef: FormArray): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
    const rowsRemaining = maxLinesAllowed - nestedFormListRef.length;
    const rowsToAdd = control.value;
    const isInvalid = isNaN(parseInt(rowsToAdd, 10)) || rowsToAdd < 0 || rowsToAdd > rowsRemaining;
    return isInvalid ? {'invalidRowCount': {value: control.value}} : null;
  };

}}

組件B HTML標記屬性

<div *ngFor="let listItem of nestedFormList.controls; index as index"
     [formGroup]="listItem">
</div>

我認為也許在子組件中使用* ngFor可能會在更改檢測期間“弄臟”視圖的值?

事實證明,問題出在操作員錯誤(如圖)。 我發現引發了此異常,因為我在HTML <input>元素上定義了一個工件“ required”屬性,而沒有說明使用Angular的Validators.required靜態方法在FormControl驗證器定義中是必需的。

將它們定義在一個位置而不是另一個位置會導致該值在第一和第二“更改檢測”例程之間更改。

所以...

          <input mdInput
               formControlName="weight"
               placeholder="Weight"
               type="text"
               aria-label="weight"
               maxlength="6"
               required>

需要從模板中刪除“必需”和“最大長度”屬性,並將其放置在FormGroup定義中,即

const prepareComponentBFormControl = (): FormGroup => {
      return formBuilder.group({
        'code': '',
        'weight': ['', Validators.required, Validators.maxlength(6)],
        'length': '',
        'width': '',
        'height': '',
      });
    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM