亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

*ngif和*ngf對同一元素造成錯誤

*ngif和*ngf對同一元素造成錯誤

暮色呼如 2019-06-20 15:20:26
*ngif和*ngf對同一元素造成錯誤我不想用角的*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在一個級別上,但對于在ul,我要么是空的,要么是空的li如果集合為空,則為liS封裝在冗余容器元素中。這個例子普朗克.注意控制臺錯誤:EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]我是做錯什么了還是這是個蟲子?
查看完整描述

3 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

我還有一個解決辦法。

使用[hidden]而不是*ngIf

<div [hidden]="!show" *ngFor="let thing of stuff">

區別在于*ngIf將從DOM中刪除元素,而[hidden]實際上是在玩CSS通過設置“顯示:無”設置樣式


查看完整回答
反對 回復 2019-06-20
  • 3 回答
  • 0 關注
  • 699 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號