【问题标题】:Angular Reactive Forms - Validation Errors - Cannot read property of undefined or nullAngular Reactive Forms - 验证错误 - 无法读取未定义或 null 的属性
【发布时间】:2019-11-11 06:28:20
【问题描述】:

我在理解一些应该很容易的事情时有一段很长的时间。表单验证。我第一次使用反应形式。我正在使用表单生成器。我有一组嵌套的控件。一般来说,我假设您创建了一组带有验证的控件,然后在模板中检查这些控件。我可以提交表单,但在尝试创建验证消息时不断出错。


------ TEMPLATE -------

<div class="container">
  <div class="row">
    <div class="col-sm">

      <!-- Begin card -->
      <div class="card border">
        <div class="card-header bg-light text-primary">
          <h3>My Account</h3>
        </div>
        <div class="card-body border border-light">
          <!-- CHANGE PASSWORD BUTTON -->
          <div class="row">
            <div class="col-sm">
              <button class="btn btn-success" (click)="goToChangePassword()">Change Password</button>
            </div>
          </div>
          <!-- Begin Form -->
          <form *ngIf="user; else loading" [formGroup]="accountForm" (ngSubmit)="updateUser()">
            <hr>
            <!-- Phone -->
            <fieldset formGroupName="phone">
              <div class="form-row">
                <div class="form-group col-sm">
                  <label>Home Phone</label>
                  <input type="number" class="form-control" formControlName="home">
                  <div *ngIf="isSubmitted && fControls.home.errors" class="invalid-feedback">
                    <div *ngIf="fControls.home.errors.minlength">10 characters min</div>
                  </div>
                </div>
                <div class="form-group col-sm">
                  <label>Mobile Phone</label>
                  <input type="number" class="form-control" formControlName="mobile">
                  <div *ngIf="isSubmitted && fControls.mobile.errors" class="invalid-feedback">
                    <div *ngIf="fControls.mobile.errors.minlength">10 characters min</div>
                  </div>
                </div>
                <div class="form-group col-sm">
                  <label>Extension</label>
                  <input type="number" class="form-control" formControlName="extension">
                  <div *ngIf="isSubmitted && fControls.extension.errors" class="invalid-feedback">
                    <div *ngIf="fControls.extension.errors.maxlength">5 chartacters max</div>
                  </div>
                </div>
              </div>
            </fieldset>

            <!-- BIRTHDAY -->
            <fieldset formGroupName="birthday">
              <div class="form-row">
                <div class="form-group col-sm-3">
                  <label>Birthday Month</label>
                  <input type="number" class="form-control" formControlName="month">
                </div>
                <div class="form-group col-sm-3">
                  <label>Birthday Day</label>
                  <input type="number" class="form-control" formControlName="day">
                </div>
              </div>
            </fieldset>
            <hr />

            <!-- BUTTONS -->
            <div class=" form-row">
              <button type="submit" class="btn btn-success mr-3" [disabled]="!accountForm.valid">Update</button>
              <button class="btn btn-danger" (click)="cancel()">Cancel</button>
            </div>


            <!-- End form -->
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- LOADING TEMPLATE -->
<ng-template #loading>
  Loading User...
</ng-template>



------ TS --------

import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/services/user.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AppToastService } from 'src/app/services/toastr.service';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.css']
})
export class AccountComponent implements OnInit {
  user;
  userId;
  accountForm: FormGroup;
  isSubmitted = false;

  constructor(
    private _userService: UserService,
    private _router: Router,
    private _toast: AppToastService,
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    // Initiate the form
    this.accountForm = this.fb.group({
      phone: this.fb.group({
        home: [' ', Validators.minLength(10)],
        mobile: [' ', Validators.minLength(10)],
        extension: [' ', Validators.maxLength(5)]
      }),
      birthday: this.fb.group({
        month: '',
        day: ''
      })
    });

    // Get userId from localstorage, then fetch the details
    this.userId = this._userService.getUserIdFromLocalStorage();

    // Get user from userId
    this._userService.getUserAccountInfo(this.userId).subscribe(
      response => {
        this.user = response['user'];
        this.accountForm.patchValue(response['user']);
      },
      error => console.log(error['message'])
    );
  }

  // Access form controls
  get fControls() {
    return this.accountForm.controls;
  }

  updateUser() {
    // Check for form validity
    this.isSubmitted = true;
    if (this.accountForm.invalid) {
      return;
    }

    let updatedUser = this.accountForm.value;
    updatedUser.id = this.userId;

    console.log(updatedUser);

  }

【问题讨论】:

  • 在任何地方使用安全导航运算符(除了模型绑定),例如*ngIf="isSubmitted &amp;&amp; fControls?.home?.errors"

标签: javascript angular angular-reactive-forms


【解决方案1】:

使用安全导航运算符 ?。它检查变量是null 还是undefined,这样我们的模板就不会尝试选择虚假的属性。

在您的情况下,在您尝试使用 . 运算符访问对象属性的模板中使用它,例如:*ngIf="isSubmitted &amp;&amp; fControls?.home?.errors"

注意:你不应该使用相同的模型绑定[(ngModel)]="employee?.name"是错误的

【讨论】:

  • 谢谢乔尔。我在模板驱动的表单中使用了这些运算符,但没有在响应式表单中使用。现在错误消失了。奇怪的是,我的验证不起作用。我对每个数字都有一个 minlength 属性,如果我尝试提交 5 个数字(少于 10 个),那么它会正确提交并且不会报告任何问题。想知道为什么会这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 2023-03-20
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-15
  • 2018-08-09
相关资源
最近更新 更多