Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading