Использование FormBuilder для создания реактивных форм выдает ошибки - PullRequest
0 голосов
/ 22 февраля 2020

Я пытаюсь закодировать реактивную форму в angular, используя для этого конструктор форм. Вот как я объявляю свою форму в отдельном файле:

import { FormGroup, FormBuilder, FormControl } from "@angular/forms";

export class AddEditCustomerForm extends FormGroup {

  constructor(builder: FormBuilder) {
    const form = builder.group({
      customerName: [''],
      address: [''],
      city: [''],
      state: [''],
      country: [''],
      zipCode: [''],
      email: [''],
      phone: [''],
      mobil: ['']
    });

    super(form.controls);
  }

  get customerName(): FormControl { return this.get('customerName') as FormControl; }
  get address(): FormControl { return this.get('address') as FormControl; }
  get city(): FormControl { return this.get('city') as FormControl; }
  get state(): FormControl { return this.get('state') as FormControl; }
  get country(): FormControl { return this.get('country') as FormControl; }
  get zipCode(): FormControl { return this.get('zipCode') as FormControl; }
  get email(): FormControl { return this.get('email') as FormControl; }
  get phone(): FormControl { return this.get('phone') as FormControl; }
  get mobil(): FormControl { return this.get('mobil') as FormControl; }
}

, а вот компонент, который использует эту форму:

import { CustomerModel } from '../../../services/api/api-client';
import { FormBuilder } from '@angular/forms';
import { AddEditCustomerForm } from './add-edit-customer.form';

@Component({
  selector: 'app-add-edit-customer',
  templateUrl: './add-edit-customer.component.html',
  styleUrls: ['./add-edit-customer.component.scss']
})
export class AddEditCustomerComponent implements OnInit {

  title: string = '';
  private _customer: CustomerModel;
  mode: string = '';
  form: AddEditCustomerForm;

  constructor(private dialogRef: MatDialogRef<AddEditCustomerComponent>,
    @Inject(MAT_DIALOG_DATA) data: { mode, customer },
    builder: FormBuilder) {

    this.form = new AddEditCustomerForm(builder);

    if (data.mode === 'NEW CUSTOMER') {
      this.title = 'ADD NEW CUSTOMER';
      this.mode = 'Add';
    } else {
      this.title = 'EDIT CUSTOMER';
      this.customer = data.customer;
      this.mode = 'Edit';
    }
  }

  get customer(): CustomerModel {
    return this._customer;
  }
  set customer(value: CustomerModel) {
    if (!value) return;

    this._customer = value;
  }

  ngOnInit() {
  }

  onSave() {
    if (this.mode === 'Add') {

    }
    else if (this.mode === 'Edit') {

    }
  }

  onClose(): void {
    this.dialogRef.close(undefined);
  }
}

это HTML:

<mat-card class="mat-elevation-z0">
  <mat-card-header class="row justify-content-between">
    <mat-card-title>
      <h4>{{title}}</h4>
    </mat-card-title>
    <button mat-icon-button type="button">
      <mat-icon>close</mat-icon>
    </button>
  </mat-card-header>
  <mat-divider></mat-divider>
  <br/>
  <mat-card-content>
    <form [formGroup]="form">
      <div fxLayout="column">
        <mat-form-field appearance="outline">
          <mat-label>Customer Name</mat-label>
          <input matInput formControlName="customerName"/>
        </mat-form-field>
        <mat-form-field appearance="outline">
          <mat-label>Address</mat-label>
          <input matInput formControlName="address"/>
        </mat-form-field>
        <div fxLayout="row" fxLayoutGap="5px">
          <mat-form-field appearance="outline">
            <mat-label>City</mat-label>
            <input matInput formControlName="city"/>
          </mat-form-field>
          <mat-form-field appearance="outline">
            <mat-label>State</mat-label>
            <input matInput formControlName="state"/>
          </mat-form-field>
        </div>
        <div fxLayout="row" fxLayoutGap="5px">
          <mat-form-field appearance="outline">
            <mat-label>Country</mat-label>
            <input matInput formControlName="country"/>
          </mat-form-field>
          <mat-form-field appearance="outline">
            <mat-label>Zip Code</mat-label>
            <input matInput formControlName="zipCode"/>
          </mat-form-field>
        </div>
        <mat-form-field appearance="outline">
          <mat-label>Email</mat-label>
          <input matInput formControlName="email"/>
        </mat-form-field>
        <div fxLayout="row" fxLayoutGap="5px">
          <mat-form-field appearance="outline">
            <mat-label>Phone</mat-label>
            <input matInput formControlName="phone"/>
          </mat-form-field>
          <mat-form-field appearance="outline">
            <mat-label>Mobil</mat-label>
            <input matInput formControlName="mobil"/>
          </mat-form-field>
        </div>
      </div>
    </form>
  </mat-card-content>
  <mat-card-actions>
    <div fxLayout="row" fxLayoutGap="5px" fxLayoutAlign="end">
      <button mat-stroked-button color="primary">Cancel</button>
      <button mat-raised-button color="primary">Save</button>
    </div>
  </mat-card-actions>
</mat-card>

Теперь, когда я запускаю приложение и нажимаю на кнопку, чтобы отобразить мой диалог в консоли, я получаю много ошибок, касающихся этого, не могу найти formControlName, вот ошибка в консоли:

AddEditCustomerComponent.html:15 ERROR Error: Cannot find control with name: 'customerName'
    at _throwError (forms.js:3357)
    at setUpControl (forms.js:3181)
    at FormGroupDirective.addControl (forms.js:7345)
    at FormControlName._setUpControl (forms.js:8070)
    at FormControlName.ngOnChanges (forms.js:7993)
    at checkAndUpdateDirectiveInline (core.js:31906)
    at checkAndUpdateNodeInline (core.js:44367)
    at checkAndUpdateNode (core.js:44306)
    at debugCheckAndUpdateNode (core.js:45328)
    at debugCheckDirectivesFn (core.js:45271)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...