Home > Enterprise >  error TS2532 Angluar : object undefined in ngIf condition
error TS2532 Angluar : object undefined in ngIf condition

Time:12-26

So in my Angular Project I have two shared files called Posters.ts and the-Posters respectfully. I defined the class Posters in the first and made a table in the-Posters.

Posters.ts

export class Posters {
    id? : string ; 
    url? : string;
    categories ? : string
    nsold? : Number;
    posterA? : boolean;
    constructor (args : Posters ={}) {
        this.id=args.id;
        this.url=args.url;
        this.categories = args.categories ;
        this.nsold = args.nsold;
        this.posterA=args.posterA;
    }
}

the-posters.ts

import { Posters } from "./posters";
export const POSTERS : Posters [] = [
{
    id : '1',
    url : '../../assets/Posters/manufacturing/p1.jpg',
    categories :"MANUFACTURING",
    nsold : 15,
    posterA : true
},
{
    id : '2',
    url : '../../assets/Posters/IT/p2.jpg',
    categories :"IT",
    nsold : 30,
    posterA : true
},
{
    id : '3',
    url : '../../assets/Posters/manufacturing/p3.jpg',
    categories :"MANUFACTURING",
    nsold : 35,
    posterA : true
}
]

and then I imported it in a component called home-user. and tried the information in home-user.component.html

home-user.component.ts

import { Component, OnInit } from '@angular/core';
import { POSTERS } from '../../shared/models/the-posters';
import { Posters } from '../../shared/models/posters';

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

  tabPosters : Posters [] = POSTERS;

  ngOnInit(): void {
  }

  

}

home-user.component.html

<h1> Manufacturing</h1>
<div *ngFor="let p of tabPosters; let i = index">
    <span *ngIf="p.categories == 'MANUFACTURING' ">
    <span *ngIf="p.posterA === true " >
    <img src="{{p.url}}" alt="">
        </span>
    </span>
</div>
<h1> IT</h1>
<div *ngFor="let p of tabPosters; let i = index">
    <span *ngIf="p.categories == 'IT' ">
    <span *ngIf="p.posterA === true " >
    <img src="{{p.url}}" alt="">
        </span>
    </span>
</div>
<h1> Best Selling</h1>
<div *ngFor="let p of tabPosters; let i = index">
    <span *ngIf=" p.nsold >30 ">
    <span *ngIf="p.posterA === true " >
    <img src="{{p.url}}" alt="">
        </span>
    </span>
</div>

and the Error is at *<span ngIf=" p.nsold >30 "> .according to Angular compiler p.nsold is undefined.

CodePudding user response:

Can you please try using the non-null assertion operator ( ! ) and see if that resolves your issue:

*ngIf="p?.nsold! > 30"
  • Related