最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - error TS2531 Object is possibly 'null' in angular reactive forms - Stack Overflow

programmeradmin9浏览0评论

I try angular reactive form validation and template driven form validation,but reactive form validation show me an error like that ,null when I try to pile and run. My angular version is 10.0.14

So, I have the ponent.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>

following is the ponent.ts file

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

     @Component({
     selector: 'app-root',
     templateUrl: './appponent.html',
     styleUrls: ['./appponent.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 './appponent';

@NgModule({
declarations: [
AppComponent,
],

imports: [
  BrowserModule,
  ReactiveFormsModule
],

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

Error is just like that

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

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

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

I try angular reactive form validation and template driven form validation,but reactive form validation show me an error like that ,null when I try to pile and run. My angular version is 10.0.14

So, I have the ponent.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>

following is the ponent.ts file

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

     @Component({
     selector: 'app-root',
     templateUrl: './app.ponent.html',
     styleUrls: ['./app.ponent.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.ponent';

@NgModule({
declarations: [
AppComponent,
],

imports: [
  BrowserModule,
  ReactiveFormsModule
],

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

Error is just like that

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

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

   ** Angular Live Development Server is listening on localhost:4200, open 
     your browser on http://localhost:4200/ **
Share Improve this question edited May 14, 2021 at 4:03 NaingMinZaw asked May 13, 2021 at 19:15 NaingMinZawNaingMinZaw 1011 silver badge7 bronze badges 3
  • 1 Can you post more of the error and where it occurred? – Phix Commented May 13, 2021 at 19:16
  • Which line is showing the error? – Gabriel Sereno Commented May 13, 2021 at 19:16
  • post error code. – Sagar V Commented May 13, 2021 at 19:31
Add a ment  | 

2 Answers 2

Reset to default 5

While your answer is correct in a sense that the error goes away and your application can pile, it does not address the problem, nor explains why it happens.

The core of the issue is, as the error message you've posted suggests, that the username property on the class could be null. This is how you define it:

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

Indeed, if you take a look at the implementation of FormGroup#get in Angular's source code, you'll see that the return type is AbstractControl | null just form the signature:

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

So even though you know that in your case form.get('userName') will surely return an instance of FormControl, Angular cannot be sure that you didn't remove it in the meantime, or change its type to something else like FormArray or FormGroup or your own custom class extending AbstractControl. The best Angular can do is tell you that's either some sort of AbstractControl, or that it's maybe null if you'd removed it in the meantime.

From the code your posted, it doesn't look like you're changing or removing userName in the signupForm, so a better solution is probably to do and explicit cast:

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

This tells TypeScript:

Look, I know what I'm doing. Yes, get could return null, but I know that it won't, for my case. So please treat this value as if its type were FormControl.

Now, in your template (and everywhere else), you can simply use {{ username.valid }}, as you originally intended.

Finally, I got this error, you can use '?' to solve this problem see the following code. Eg;

 *ngIf="username?.invalid"
发布评论

评论列表(0)

  1. 暂无评论