简体   繁体   中英

Angular 4 using nested *ngFor correctly

I am implementing an update webservice. For that I am fetching data from database and populating the form fields with it. The user then needs to edit the data and submit it to update the database.

I need help implementing this with checkboxes. I am trying to use nested *ngFor to fetch 2 different webservices. "maintainanceTypeList" contains all the checkbox options and "defaultmaintainance" contains the options that were checked when user submitted the create form. As you can see I am trying to compare the id of the two and check the checkbox when the comparison returns true.

My problem is that iterations of the nested loops now depend on how many objects my defaultmaintainance has which means same checkboxes are displayed multiple times.

<label for="maintenancetype"
       class="text-3ab08b text-transform"
       style="margin-right: 1em;">
    Maintenance Type:
</label>
<span *ngFor="let x of maintainanceTypeList">
    <span *ngFor="let y of defaultmaintainance">
        <md-checkbox *ngIf="x.isDeleted == 0" 
                     name="{{x.maintenancetype}}" 
                     [checked]="x._id == y._id"
                     (change)="changeMaintainance($event.checked, x)" 
                     value="{{x.maintenancetype}}">
            {{x.maintenancetype}}
        </md-checkbox>
    </span>
</span>

edit: Both the arrays are array of objects with multiple objects in this format:

isDeleted:"0"
maintenancetype:"Fixed"
status:"1"
_id:"5971da2c958ccd42a9c99f54"

I would modify maintainanceTypeList adding to each it's item an additional property which shows should this item be checked or not:

let selectedIds = defaultmaintainance.map(item => item._id);

maintainanceTypeList.forEach(checkbox => {
    checkbox.checked = (selectedIds.indexOf(checkbox._id) > -1) ? true : false;
})

And then display maintainanceTypeList within a single *ngFor loop:

<span *ngFor="let x of maintainanceTypeList">
    <md-checkbox *ngIf="x.isDeleted == 0" 
                 name="{{x.maintenancetype}}" 
                 [checked]="x.checked"
                 (change)="changeMaintainance($event.checked, x)" 
                 value="{{x.maintenancetype}}">
        {{x.maintenancetype}}
    </md-checkbox>
</span>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM