【问题标题】:Object is possibly "null" TS2531 angular-reactive forms对象可能是“空”TS2531 角度反应形式
【发布时间】:2021-10-21 02:23:16
【问题描述】:

我尝试在 Angular 中进行反应式表单验证,但出现错误。我的目标是让程序在用户将必填字段留空时警告用户。

product-add-forms2.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Product } from '../product';

@Component({
  selector: 'app-product-add-forms2',
  templateUrl: './product-add-forms2.component.html',
  styleUrls: ['./product-add-forms2.component.css']
})
export class ProductAddForms2Component implements OnInit {

  constructor(private formBuilder: FormBuilder) { }

  productAddForm: FormGroup;
  product: Product = new Product();

  createProductAddForm() {
    this.productAddForm = this.formBuilder.group({
      name: ["", Validators.required],
      description: ["", Validators.required],
      imageUrl: ["", Validators.required],
      price: ["", Validators.required],
      categoryId: ["", Validators.required],
    });
  }



  ngOnInit(): void {
    this.createProductAddForm();
  }

  add() {
    if (this.productAddForm.valid) {
      this.product = Object.assign({}, this.productAddForm.value)
    }
  }

}

product-add-forms2.component.html

<h3>New Product - Reactive</h3>
<form [formGroup]="productAddForm" (ngSumbit)="add()" class="form-group">
  <div>
    <input type="text" id="name" name="name" formControlName="name" class="form-control" placeholder="Ürün Adı">
    <div class="alert alert-danger"
      *ngIf="productAddForm.get('name').hasError('required') && productAddForm.get('name').dirty">Product name is required
    </div>
  </div>
</form>


当我运行它的显示错误时

<div class="alert alert-danger"
  *ngIf="productAddForm.get('name').hasError('required') && productAddForm.get('name').dirty">Product name is required
</div>

我正在谈论的部分 (hasError) 和 (dirty)

【问题讨论】:

标签: angular angular-reactive-forms reactive-forms


【解决方案1】:

从 Angular 12 开始,Typescript 中的严格检查默认启用。 您可以禁用它或使用! 运算符。 例如: 更改productAddForm: FormGroup;productAddForm!: FormGroup; ! 表示我现在知道它为 null,但它应该在运行时定义。

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 2021-05-04
    • 2022-01-22
    • 2021-07-11
    • 1970-01-01
    • 2021-02-14
    • 2021-08-27
    • 1970-01-01
    相关资源
    最近更新 更多