错误 TS2531 对象可能以角度反应形式为“空”

时间:2021-05-13 19:15:04

标签: javascript html css angular typescript

我尝试了角度反应式表单验证和模板驱动的表单验证,但是当我尝试编译和运行时,反应式表单验证向我显示了这样的错误,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/ **

2 个答案:

答案 0 :(得分: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,如果你在此期间删除了它。

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

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

这告诉 TypeScript:

<块引用>

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

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

答案 1 :(得分:0)

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

 *ngIf="username?.invalid"