Reputation:
I try to make a filter method this method works well but I have an error: cannot convert undefined or null to object that I cannot solve
example json
{
"toto": [
"titi",
"tata"
],
hideString: [], // filter method hide this element
"foo": [
"foobar",
"footix"
]
}
card.components.ts
@Input() toto: ISummary[] = []
getKeys() {
Object.keys(this.toto).filter(key => this.toto[key].lenght > 0)
// in my console I have the following error: cannot convert undefined or null to object
the error comes from this line
}
totoa(keys:string){
return this.toto[key]
}
card.html
<div *ngFor="let keys of getKeys()">
{{keys}}
<div *ngFor="let values of totoa(keys)">
{{values}}
</div
</div
home.components.ts
public result: string = '';
public toto?: Observable<ISummary[]>; // maybe the problem comes from Here I have ternary operator '?'
ngOnInit() {
this.activatedRoute.paramMap.subscribe(params = > {
let bigramme = params.get('bigramme');
this.result = bigramme as string;
getSummary();
}
}
getSummary() {
this.toto = this.sumService.getAllSummary(this.result);
}
Upvotes: 0
Views: 8822
Reputation: 9903
The cannot convert undefined or null to object Angular
error is occurred when you try Object.keys(null)
. So you can check the object you want to pass to object.keys
.
But
It seems you want to show some data in your html based on key/value
, so there is a keyvalue
pipe for this purpose and no need to extra code such as totoa
methods.
And for hiding empty value simply use [hidden]
<div *ngFor="let item of testObject | keyvalue" [hidden]="item.value.length == 0">
Key: <b>{{item.key}}</b>
<div *ngFor="let item1 of item.value">
Value: <b>{{item1}}</b>
</div>
<br>
</div>
Here is working sample
The result:
Upvotes: 1
Reputation: 4908
You have to check it before using toto
object.
The ? can also be used to null/undefined issue, like :
this.toto[key]?.something(); // will not throw error if toto[key] is not defined
But I think you are trying to get keys of toto before setting it, so I suggest you soemthing like :
public summarykeys: string[] = [];
@Input() toto: ISummary[] = []
getKeys() {
return this.toto ? this.summarykeys.Object.keys(this.toto).filter(key => this.toto[key].lenght > 0) : [];
}
totoa(keys: string){
return this.toto[key]
}
Upvotes: 1