Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda