【问题标题】:Object is possibly 'null' in Reactive Forms Angular对象在反应形式 Angular 中可能为“空”
【发布时间】:2021-08-12 09:59:38
【问题描述】:

我需要你的帮助!我是 Angular Reactive Forms 的新手,我正在尝试使用 Angular 的 Reactive Forms 制作简单的表单并进行验证。但我在这部分代码中遇到错误(ngIf 指令,属性“无效”):

<div class="container">
  <form class="card" [formGroup]="form" (ngSubmit)="submit()">
    <h1>Angular Forms</h1>

    <div class="form-control">
      <label>Email</label>
      <input type="text" placeholder="Email" formControlName="email">
      <div
        *ngIf="form.get('email').invalid" 
        class="validation">
      </div>
    </div>

    <div class="form-control">
      <label>Пароль</label>
      <input type="password" placeholder="Пароль" formControlName="password">
      <div class="validation"></div>
    </div>

    <div class="card">
      <h2>Адрес</h2>

      <div class="form-control">
        <label>Страна</label>

        <select>
          <option value="ru">Россия</option>
          <option value="ua">Украина</option>
          <option value="by">Беларусь</option>
        </select>
      </div>

      <div class="form-control">
        <input type="text">
      </div>

      <button class="btn" type="button">Выбрать столицу</button>
    </div>

    <div class="card">
      <h2>Ваши навыки</h2>
      <button class="btn" type="button">Добавить умение</button>
      <div class="form-control">
        <label></label>
        <input type="text">
      </div>
    </div>

    <button class="btn" type="submit" [disabled]="form.invalid">Отправить</button>

  </form>
</div>

TypeScript 代码:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
  title = 'forms';
  form!: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({
      email: new FormControl('',
        [Validators.email,
         Validators.required]),
      password: new FormControl(null,
        [Validators.required,
         Validators.minLength(8)])
    })
  }

  submit() {
    console.log('Form submitted', this.form);
    const formData = { ...this.form.value };

    console.log('Form Data:', formData);

  }
}

我使用 Angular 12 并遵循 Udemy 上的指南,所以这很奇怪,因为我导师的代码是正确的。我创建了 FromGroup 和 FormControls,给它们起了名字,所以我对这个错误感到非常困惑。您有什么想法可以解决吗?

【问题讨论】:

  • 提供更多代码

标签: html angular reactive-forms


【解决方案1】:

Object is possibly 'null' 错误可能由于严格的类型检查而发生,可以通过两种方式解决:

  • 使用!(非空断言运算符)断言您绝对确定永远不会为空
  • 使用?(可选链接运算符)阻止最终错误发生,以防对象确实为空

所以你可以用form.get('email')?.invalid 替换if 语句,它应该可以工作。 here 也有人问过类似的问题。

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2021-08-04
    • 2021-05-04
    • 2021-10-21
    • 2021-12-04
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多