I have a problem with nested *ngfor in angular 4, what i need to do is delete parent ngfor i have tried with setting it to null and using delete and neither works so i am kinda out of options. basically what happens if you delete parent ngFor angular misbehaves(at least i think) and throws error.
Can you guys help me out and show me the correct way to do nested *ngfor in which it is possible to remove children, or now in angular 4 it is done on some different way?
i have created this test component
@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 is the error, can't read much from it other than it tried to read items of null, if i try delete than same error instead of null of undefined, do i somehow need to tell data is changed that part isn't magical any more? If i try this.data.categories[0] = [] or = {} it updates fine the thing is i want to delete data because i want to pass it to server, and because user pressed delete :'( can't believe something like that simply isn't possible?
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)
For removing item from Array
, you should use Array.splice(index, length)
.
using delete
will make the item tobe undefined
, but still there(an item of the Array). same with setting to null
. And for your situation, this will leads to error cannot find something of null/undefined
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.