2017-04-09 57 views
-1

我有一個嵌套的* ngfor在角度4的問題,我需要做的是刪除父ngfor我已經嘗試將其設置爲空和使用刪除,既不工作,所以我是沒有選擇。基本上會發生什麼,如果你刪除父ngForFor錯誤行爲(至少我認爲)並拋出錯誤。角度4嵌套* ngFor上刪除父錯誤

你們可以幫我解決,讓我看看正確的方法來做嵌套的* ngfor,在其中可以刪除孩子,或者現在在角度4,它是以不同的方式完成的?

我創造了這個測試組件

@Component({ 
 
    selector: 'test-parent', 
 
    templateUrl: './test.component.html', 
 
}) 
 
export class TestComponent { 
 
    constructor() { 
 
     console.log("loaded menu"); 
 
     setTimeout(()=> { 
 
      this.data.categories[1] = null; 
 
     }, 1000); 
 
    }; 
 
    data = { 
 
     categories: [ 
 
      { 
 
       name: 'name 1', 
 
       items: [ 
 
        { 
 
         name: 'item 1' 
 
        }, 
 
        { 
 
         name: 'item 2' 
 
        }, 
 
       ] 
 
      }, 
 
      { 
 
       name: 'name 2', 
 
       items: [ 
 
        { 
 
         name: 'item 3' 
 
        } 
 
       ] 
 
      } 
 
     ] 
 
    } 
 
}
<div *ngFor="let c of data.categories"> 
 
    {{c.name}} 
 
    <div *ngFor="let i of c.items"> 
 
     {{i.name}} 
 
    </div> 
 
</div>

這是錯誤,無法從它的其他讀得多比它試圖讀取空的項目,如果我嘗試刪除比同樣的錯誤,而不是空的未定義, 我不知道需要告訴數據改變,該部分是不是神奇更多?如果我嘗試this.data.categories [0] = []或= {}它更新正常的事情是我想刪除數據,因爲我想傳遞給服務器,並且因爲用戶按下刪除:'(不能相信這樣的事情根本是不可能的?

ERROR TypeError: Cannot read property 'items' of null 
at Object.View_TestComponent_1.currVal_0 [as updateDirectives] (TestComponent.html:3) 
at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12613) 
at checkAndUpdateView (core.es5.js:12025) 
at callViewAction (core.es5.js:12340) 
at execEmbeddedViewsAction (core.es5.js:12312) 
at checkAndUpdateView (core.es5.js:12026) 
at callViewAction (core.es5.js:12340) 
at execComponentViewsAction (core.es5.js:12286) 
at checkAndUpdateView (core.es5.js:12031) 
at callViewAction (core.es5.js:12340) 
at execEmbeddedViewsAction (core.es5.js:12312) 
at checkAndUpdateView (core.es5.js:12026) 
at callViewAction (core.es5.js:12340) 
at execComponentViewsAction (core.es5.js:12286) 
at checkAndUpdateView (core.es5.js:12031) 
+0

爲什麼不拼接數組?有沒有理由不起作用? –

+0

我已經嘗試過它與這個測試場景一起工作,但是tbh我喜歡4個嵌套for循環槽不同組件,altought它應該工作我得到這個相同的錯誤 –

回答

2

對於從Array刪除的項目,你應該使用Array.splice(index, length)


使用delete將使項目砥undefined,但仍然存在(的項目陣列),設置爲null。 對於你的情況,這個無線會導致錯誤cannot find something of null/undefined

+0

非常感謝你的工作,我以爲我已經嘗試過它, t工作,反正不刪除完全刪除數組成員? –

+0

@VjeranMagisterLudi還有問題嗎? – Pengyy

+0

nop它是固定的,我現在正在做一些廣泛的測試 –