angular - *ngIf and *ngFor on same element causing error -
i'm having problem trying use angular's *ngfor
, *ngif
on same element.
when trying loop through collection in *ngfor
, collection seen null
, consequently fails when trying access properties in template.
@component({ selector: 'shell', template: ` <h3>shell</h3><button (click)="toggle()">toggle!</button> <div *ngif="show" *ngfor="let thing of stuff"> {{log(thing)}} <span>{{thing.name}}</span> </div> ` }) export class shellcomponent implements oninit { public stuff:any[] = []; public show:boolean = false; constructor() {} ngoninit() { this.stuff = [ { name: 'abc', id: 1 }, { name: 'huo', id: 2 }, { name: 'bar', id: 3 }, { name: 'foo', id: 4 }, { name: 'thing', id: 5 }, { name: 'other', id: 6 }, ] } toggle() { this.show = !this.show; } log(thing) { console.log(thing); } }
i know easy solution move *ngif
level scenarios looping on list items in ul
, i'd end either empty li
if collection empty, or li
s wrapped in redundant container elements.
example @ plnkr.
note console error:
exception: typeerror: cannot read property 'name' of null in [{{thing.name}} in shellcomponent@5:12]
am doing wrong or bug?
angular2 doesn't support more 1 structural directive on same element.
workaround use <ng-container>
element allows use separate elements each structural directive, not stamped dom.
<ng-container *ngif="show"> <div *ngfor="let thing of stuff"> {{log(thing)}} <span>{{thing.name}}</span> </div> </ng-container>
<template>
(<ng-template>
in angular4) allows same different syntax confusing , no longer recommended
<template [ngif]="show"> <div *ngfor="let thing of stuff"> {{log(thing)}} <span>{{thing.name}}</span> </div> </template>
Comments
Post a Comment