简体   繁体   中英

Angular 5 ExpressionChangedAfterItHasBeenCheckedError on form validation

I have a form as listed below. However, when I enter the page containing this form, it doesn't load properly. The values are not correct and the console gives the ExpressionChangedAfterItHasBeenChecked Error. All the values are the same as the last field: darts_thrown . The 'player' is an object from the database and these values are correct when I log them, but somehow they change somewhere.

<div class="container">
  <ngx-flash-messages></ngx-flash-messages>

  <form *ngIf="player != null" (ngSubmit)="onSubmit()" [(formGroup)]="userForm">
    <div class="form-group row">
      <label for="name">Name</label>
      <input class="form-control" required name="name" formControlName="name" type="text" id="name" [(ngModel)]="player.name">
    </div>

    <div *ngIf="name.invalid && (name.dirty || name.touched)"
         class="alert alert-danger">
      <div *ngIf="name.errors.required">
        Name can't be empty.
      </div>
      <div *ngIf="name.errors.minLength">
        Name must be at least two characters.
      </div>
      <div *ngIf="name.errors.maxLength">
        Name must be less than thirty characters.
      </div>
    </div>

    <div class="form-group row">
      <label for="email">Email</label>
      <input class="form-control" required name="email" formControlName="name" type="text" id="email" [(ngModel)]="player.email">
    </div>

    <div class="form-group row">
      <label for="games_won">Games won</label>
      <input class="form-control" required name="games_won" formControlName="name" type="number" id="games_won" [(ngModel)]="player.games_won">
    </div>

    <div class="form-group row">
      <label for="darts_thrown">Darts thrown</label>
      <input class="form-control" required name="darts_thrown" formControlName="name" type="number" id="darts_thrown" [(ngModel)]="player.darts_thrown">
    </div>

    <div class="row">
      <input class="btn btn-primary" style="color: #fff !important;" type="submit" value="Verander de gebruiker!">
    </div>
  </form>
</div>

The component.ts:

    import {Component} from '@angular/core';
    import {PlayerService} from '../../player.service';
    import {ActivatedRoute, Router} from '@angular/router';
    import {FlashMessagesService} from 'ngx-flash-messages';
    import {FormControl, FormGroup, Validators} from '@angular/forms';

    @Component({
      selector: 'app-player-edit',
      templateUrl: './player-edit.component.html',
      styleUrls: ['./player-edit.component.scss']
    })
    export class PlayerEditComponent {
      player: any;
      userForm: any;

      constructor(private playerService: PlayerService, private messageService: FlashMessagesService, route: ActivatedRoute, router: Router) {
        if (route.snapshot.params.id) {
          playerService.getPlayer(route.snapshot.params.id).subscribe(data => {
            if (data['status'] === 'success') {
              this.player = data['user'];
              this.userForm = new FormGroup({
                'name': new FormControl(this.player.name, [Validators.minLength(2), Validators.maxLength(30),
                  Validators.required]),
                'email': new FormControl(this.player.email, [Validators.minLength(2), Validators.maxLength(30),
                  Validators.email, Validators.required]),
                'games_won': new FormControl(this.player.games_won, [Validators.required, Validators.pattern('[0-9]*')]),
                'darts_thrown': new FormControl(this.player.darts_thrown, [Validators.required, Validators.pattern('[0-9]*')])
              });
            } else {
              router.navigate(['/players/index']);
            }
          });
        } else {
          router.navigate(['/players/index']);
        }
      }

      get name() { return this.userForm.get('name'); }
      get email() { return this.userForm.get('email'); }
      get games_won() { return this.userForm.get('games_won'); }
      get darts_thrown() { return this.userForm.get('darts_thrown'); }
    }

Important comments should be in answer, please reward points to Thirueswaran Rajagopalan

If Im correct you are doing things via Reactive-Forms, so you dont need to use [(ngModel)]. Please check on angular.io/guide/reactive-forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM