Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
Form Group getting 'null' or 'undefined' error

i have a component.ts that looks like this :

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Observable, Subscription} from "rxjs";
import {ArticleService} from "../article.service";

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

  response$?: Subscription;

  constructor(private formBuilder: FormBuilder, private articleService: ArticleService) { }

  articleForm: FormGroup = this.formBuilder.group({
    title: ['', Validators.required],
    content: ['', [Validators.required, Validators.minLength(69)]]
  })

  ngOnInit(): void {
  }

  async submit(){
    console.log('article / sub', this.articleForm.value);
    this.response$ = await this.articleService.createArticle(this.articleForm.value).subscribe(
      res => console.log(res)
    );
  }

  get title() {
    return this.articleForm.get('title');
  }

  get content() {
    return this.articleForm.get('content');
  }
}

And the html of the component :

<h3>Create New Article</h3>
<form [formGroup]="articleForm" (ngSubmit)="submit()">
  <div class="form-group">
    <label for="title">Title :</label>
    <input type="text" formControlName="title" class="form-control" id="title" required>
    <div *ngIf="title?.invalid" class="alert alert-danger">
      Title is required
    </div>
  </div>

  <div class="form-group">
    <label for="content">Content :</label>
    <textarea class="form-control" formControlName="content" id="content" rows="3" required></textarea>
    <div *ngIf="content?.errors && (content?.errors['required'] !== null)" class="alert alert-danger">
      Content is required
    </div>
    <div *ngIf="content?.errors && (content?.errors['minLength'] !== null)" class="alert alert-danger">
      Minimum length
    </div>
  </div>

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

As you can see, i have 3 divs with *ngIf. The first one with "Title" gave me a similar error that i solved by adding "?" after the variable name.

But with the content variable, adding the question mark didn't change anything. So i have that error for those 2 divs :

TS2533: Object is possibly 'null' or 'undefined'.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Yes, this is strict checking and having "long" paths like (content?.errors['required'] !== null will cause such things. It should clear up by using

content?.errors?.required 

but I do prefer using hasError instead, so that is what I would suggest you to use, better readability in my opinion ;) So that would mean simply

content?.hasError('required')

and that can be applied to every formcontrol in your form, any validators. Please not that there is a gotcha with minLenght and maxLength. The L needs to be lowercase, so:

content?.hasError('minlength')
about 4 years ago · Juan Pablo Isaza Denunciar

0

Try to use this :

articleForm= new FormGroup({
     title: new FormControl('', Validators.required),
     content: new FormControl('', [Validators.required, Validators.minLength(69)])
}); 

See this documentation : https://www.concretepage.com/angular-2/angular-2-formgroup-example

about 4 years ago · Juan Pablo Isaza Denunciar

0

Move the form creation logic inside ngOnInit hook

  ngOnInit(): void {
     this.buildForm();
  }
  
  buildForm():void{
    this.articleForm = this.formBuilder.group({
      title: ['', Validators.required],
      content: ['', [Validators.required, Validators.minLength(69)]]
    })
  }

and add check in html part for articleForm

<form *ngIf="articleForm" [formGroup]="articleForm" (ngSubmit)="submit()">
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda