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

170
Visualizações
Getting undefined object error in Typescript using Angular

So I am following the Traversy Media new [Angular crash course]: https://www.youtube.com/watch?v=3dHNOWTI7H8 around 39:45 and getting object undefined errors constantly.

Here is the picture of the error which says object is possibly 'undefined': object is possibly 'undefined

This worked in task-item.component.html

<p *ngFor="let task of tasks">
  {{task.text}}
</p>

This object is possibly 'undefined' task-item.component.html

<div class="task">
    <h3>{{task.text}}</h3>
    <p>{{task.day}}</p>
</div>

task-item.component.ts

import { Component, OnInit, Input } from '@angular/core';
    import {Task} from 'src/Task';
    
    @Component({
      selector: 'app-task-item',
      templateUrl: './task-item.component.html',
      styleUrls: ['./task-item.component.css']
    })
    export class TaskItemComponent implements OnInit {
      @Input() task?: Task;
    
      constructor() {
      }
    
      ngOnInit(): void {
      }
    
    }

I have put a tsconfig.json rule "strictPropertyInitialization": false

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

It's because you set it as a an optional using ?

You can either remove ? which is not a good practice if your item can be null, or you can just do this in the html

<div class="task">
  <h3>{{task?.text}}</h3>
  <p>{{task?.day}}</p>
</div>

It will display the value if the variable is initialized, and don't throw an error

about 4 years ago · Juan Pablo Isaza Relatório

0

The ? here indicates that this is a nullable object.

@Input() task?: Task;

If you always pass task to app-task-item then just remove the ?

@Input() task: Task;

Or you can add a conditional in your html, and remove the ? in your .ts

@Input() task: Task;
...
<div class="task">
  <h3>{{task?.text}}</h3>
  <p>{{task?.day}}</p>
</div>
about 4 years ago · Juan Pablo Isaza Relatório

0

To solve this I add *ngIf

  <div class="task" *ngIf="task">
      <h3>{{task.text}}</h3> 
      <p>{{task.day}}</p> 
    </div>
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