我在与试图使用角度的问题*ngFor,并*ngIf在相同的元素。
当尝试遍历中的集合时*ngFor,该集合被视为null,因此在尝试访问其在模板中的属性时失败。
@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);
  }
}我知道简单的解决方案是将其*ngIf上移,但是对于诸如循环遍历a中的列表项之类的方案ul,li如果集合为空,则最终将为空,或者li将其包装在冗余容器元素中。
此plnkr的示例。
注意控制台错误:
EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]
我是在做错什么还是错误?