I have a service with the name “logManagerService”
import { Injectable } from '@angular/core';
@Injectable({
// this line code make this service as singleton.
providedIn: 'root'
})
export class logManagerService {
private ErrorMessages:string[];
constructor() {
this.ErrorMessages=[];
}
public getErrorMassages():string[]{
return this.ErrorMessages;
}
}
in the component “display-log.component.html”, I want to display the content of “ErrorMessages” array. Although I use a question mark in order to check undefined in ngif clause, I get an error “Object is possibly 'undefined' “
<div *ngIf="**logManagerService?.getErrorMassages()?.length>0** " class="alert alert-danger">
**<!--Object is possibly 'undefined' -->**
<h5>
Errors
</h5>
<ul>
<li *ngFor="let M of logManagerService.getErrorMassages()">
{{M}}
</li>
</ul>
</div>
How can I fix it?
You can try this:
$any(logManagerService?.getErrorMassages())?.length > 0