{"id":518,"hash":"a5c53eac60c6df958c63df7ebbeb15bb3a62e2f7b00573ad1d37c01341b7475d","pattern":"*ngIf and *ngFor on same element causing error","full_message":"I'm having a problem with trying to use Angular's *ngFor and *ngIf on the same element. \n\nWhen trying to loop through the collection in the *ngFor, the collection is seen as null and consequently fails when trying to access its properties in the template.\n\n@Component({\n  selector: 'shell',\n  template: `\n    <h3>Shell</h3><button (click)=\"toggle()\">Toggle!</button>\n\n    <div *ngIf=\"show\" *ngFor=\"let thing of stuff\">\n      {{log(thing)}}\n      <span>{{thing.name}}</span>\n    </div>\n  `\n})\n\nexport class ShellComponent implements OnInit {\n\n  public stuff:any[] = [];\n  public show:boolean = false;\n\n  constructor() {}\n\n  ngOnInit() {\n    this.stuff = [\n      { name: 'abc', id: 1 },\n      { name: 'huo', id: 2 },\n      { name: 'bar', id: 3 },\n      { name: 'foo', id: 4 },\n      { name: 'thing', id: 5 },\n      { name: 'other', id: 6 },\n    ]\n  }\n\n  toggle() {\n    this.show = !this.show;\n  }\n\n  log(thing) {\n    console.log(thing);\n  }\n\n}\n\nI know the easy solution is to move the *ngIf up a level but for scenarios like looping over list items in a ul, I'd end up with either an empty li if the collection is empty, or my lis wrapped in redundant container elements.\n\nExample at this plnkr.\n\nNote the console error:\n\nEXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]\n\nAm I doing something wrong or is this a bug?","ecosystem":"npm","package_name":"angular","package_version":null,"solution":"Angular v2 doesn't support more than one structural directive on the same element.\n\nAs a workaround use the <ng-container> element that allows you to use separate elements for each structural directive, but it is not stamped to the DOM.\n\n<ng-container *ngIf=\"show\">\n  <div *ngFor=\"let thing of stuff\">\n    {{log(thing)}}\n    <span>{{thing.name}}</span>\n  </div>\n</ng-container>\n\nUpdates for Angular v17 and beyond\n\nThe <ng-container> approach can no longer be recommended, since the introduction of the control flow in Angular v17.\n\n@if(show){\n  @for(thing of stuff; track thing.id){\n  <div>\n    {{log(thing)}}\n    <span>{{thing.name}}</span>\n  </div>\n }\n}","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/34657821/ngif-and-ngfor-on-same-element-causing-error","votes":660,"created_at":"2026-04-19T04:51:17.797119+00:00","updated_at":"2026-04-19T04:51:17.797119+00:00"}