FormBuilder в reactiveForms в Angular 9 с ясностью работает, но отправляет ошибку - PullRequest
0 голосов
/ 28 мая 2020

У меня проблема с моими angular реактивными формами в Angular с ясностью. Все работает отлично, но если я нажимаю несколько раз, в консоли появляется ошибка, и мой первый ввод ничего не показывает.

Не знаю почему ...

Мой код component.ts:

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { FormGroup, Validators, FormBuilder } from '@angular/forms';
    import { ClrForm } from '@clr/angular';

    import { Entreprise } from '@models/entreprise-model';
    import { EntrepriseService } from '@services/entreprise.service';
    import { Router } from '@angular/router';


    @Component({
        selector: 'app-entreprise-edit',
        templateUrl: './entreprise-edit.component.html',
        styleUrls: ['./entreprise-edit.component.scss']
    })
    export class EntrepriseEditComponent implements OnInit {
     @ViewChild(ClrForm, {static: true}) clrForm;

     updateEntForm: FormGroup;
     entreprise: Entreprise;
     loading = false;

     constructor(
       private entrepriseService: EntrepriseService,
       private formBuilder: FormBuilder,
       private router: Router,
       ) { }

  ngOnInit() {
    this.entrepriseService.findEnt()
      .subscribe(
        (ent) => {
        this.entreprise = ent.data;
        this.initForm();
      });
  }

  initForm() {
    this.updateEntForm = this.formBuilder.group({
      nameEnt: [this.entreprise.nameEnt, [Validators.required]],
      ville: [this.entreprise.ville, [Validators.required]],
      numSiret: [this.entreprise.numSiret, [Validators.required, Validators.minLength(14), Validators.maxLength(14)]],
      nbr_couvert: [this.entreprise.nbr_couvert, [Validators.required]],
    });
  }

  onSubmit() {
    if (!this.updateEntForm.valid) {
      this.clrForm.markAsTouched();
      return;
    }
    this.loading = true;
    this.entrepriseService.updateEnt(this.entreprise.id, this.updateEntForm.value)
    .subscribe(
      (ent) => {
        this.loading = false;
        this.entreprise = ent.data;
        this.router.navigate(['/dashboard/entreprise']);
      },
      (error: Error) => {
        this.loading = false;
        console.log(error);
      });
  }

}

Мой кодовый компонент. html:

<form clrForm clrLayout="horizontal" [formGroup]="updateEntForm" class="form form--no-cols"
                (ngSubmit)="onSubmit()">

                <clr-input-container class="input-icon input-icon--nameEnt">
                    <label for="nameEnt">Le nom</label>
                    <input clrInput id="nameEnt" type="text" formControlName="nameEnt" name="nameEnt" required />
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!</clr-control-error>
                </clr-input-container>

                <clr-input-container class="input-icon input-icon--letter">
                    <label for="ville">La ville</label>
                    <input id="ville" clrInput type="text" formControlName="ville" name="ville" required />
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!</clr-control-error>
                </clr-input-container>

                <clr-input-container class="input-icon input-icon--nameEnt">
                    <label for="numSiret">Votre numéro de Siret:</label>
                    <input clrInput id="numSiret" type="number" formControlName="numSiret" name="numSiret"
                        required />
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!
                    </clr-control-error>
                </clr-input-container>

                <clr-input-container class="input-icon input-icon--letter">
                    <label for="nbr_couvert">Le nombre de couvert:</label>
                    <input clrInput id="nbr_couvert" type="number" formControlName="nbr_couvert" name="nbr_couvert"
                         required>
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!
                    </clr-control-error>
                </clr-input-container>

            </form>

У меня разные ошибки:

ERROR Error: "formGroup expects a FormGroup instance. Please pass one in.

       Example:


    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });"
ERROR TypeError: "ctx.ent is undefined"
ERROR TypeError: "this.form is undefined"
ERROR TypeError: "this.control.statusChanges is null"

Если у кого-то есть идея ...

1 Ответ

0 голосов

Сегодня я привел довольно хороший пример использования рекреационных форм, а также указал, какие 3 элемента составляют реактивные формы

Тема

Что касается присвоения данных к форме, лучше использовать вот так

constructor(private appService: appService) {
    if (this.route.snapshot.paramMap.get('id')) {
        this.id = Number(this.route.snapshot.paramMap.get('id'));
        this.appService.getData(this.id).subscribe(result => {
            this.model = result;
            this.formBasic.controls['id'].setValue(this.model.id);
            this.formBasic.controls['name'].setValue(this.model.name);
    }
}
...