【问题标题】:error TS2531 Object is possibly 'null' in angular reactive forms错误 TS2531 对象可能在角度反应形式中为“空”
【发布时间】:2021-08-04 01:47:28
【问题描述】:

我尝试了角度响应式表单验证和模板驱动表单验证,但是当我尝试编译和运行时,响应式表单验证向我显示了这样的错误,null。我的角度版本是 10.0.14

所以,我有component.html

<form action=""
  [formGroup]="singupForm"
  (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="">Username</label>
      <input
      type="text"
      id="userName"
      class="form-control"
      formControlName="userName"
      >
      <span
      *ngIf="username.invalid"
      class="help-block"
      >Please enter valid username!</span>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>

下面是component.ts文件

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

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

    singupForm! : FormGroup;
    constructor(){}

    ngOnInit(){
     this.singupForm = new FormGroup({
     userName : new  FormControl(null, Validators.required)
     });
     }
       get username(){
        return this.singupForm.get('userName');
         }

         onSubmit(){
          console.log(this.singupForm.value)
         }

} app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
declarations: [
AppComponent,
],

imports: [
  BrowserModule,
  ReactiveFormsModule
],

   providers: [],
   bootstrap: [AppComponent]
   })
 export class AppModule { }

错误就是这样

   ERROR in src/app/app.component.html:16:27 - error TS2531: Object is 
   possibly 'null'.

   16           *ngIf="username.invalid"
                         ~~~~~~~ src/app/app.component.ts:6:16
   6   templateUrl: './app.component.html',
                 ~~~~~~~~~~~~~~~~~~~~~~
  Error occurs in the template of component AppComponent.

   ** Angular Live Development Server is listening on localhost:4200, open 
     your browser on http://localhost:4200/ **

【问题讨论】:

  • 您能否发布更多错误信息以及错误发生的位置?
  • 哪一行显示错误?
  • 发布错误代码。

标签: javascript html css angular typescript


【解决方案1】:

虽然your answer 在某种意义上是正确的,即错误消失并且您的应用程序可以编译,但它并没有解决问题,也没有解释为什么会发生。

问题的核心是,正如您发布的错误消息所示,该类的username 属性可能是null。这就是你定义它的方式:

get username () {
  return this.singupForm.get('userName')
}

确实,如果你看一下the implementation of FormGroup#get in Angular's source code,你会看到返回类型是AbstractControl | null,只是形成签名:

get (path: Array<string|number>|string): AbstractControl | null

所以即使知道在你的情况form.get('userName')肯定会返回一个FormControl的实例,Angular也不能确定你没有删除它同时,或者将其类型更改为 FormArrayFormGroup 或您自己的扩展 AbstractControl 的自定义类。 Angular 能做的最好的事情就是告诉你它要么是某种AbstractControl,要么是null,如果你同时删除了它的话。

从您发布的代码来看,您似乎并没有更改或删除 signupForm 中的 userName,因此更好的解决方案可能是进行显式转换:

get username () {
  return this.singupForm.get('userName') as FormControl
}

这告诉 TypeScript:

听着,我知道我在做什么。是的,get 可以返回 null,但知道它不会,我的情况。所以请将此值视为其类型为FormControl

现在,在您的模板(以及其他任何地方)中,您可以按照最初的意图简单地使用 {{ username.valid }}

【讨论】:

    【解决方案2】:

    最后,我得到了这个错误,你可以使用 '?'解决这个问题 请参阅以下代码。例如;

     *ngIf="username?.invalid"
    

    【讨论】:

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