简体   繁体   English

Angular 4使用嵌套* ng

[英]Angular 4 using nested *ngFor correctly

I am implementing an update webservice. 我正在实施更新Web服务。 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. 我正在尝试使用嵌套的* ngFor来获取2种不同的Web服务。 "maintainanceTypeList" contains all the checkbox options and "defaultmaintainance" contains the options that were checked when user submitted the create form. “ maintainanceTypeList”包含所有复选框选项,“ defaultmaintainance”包含用户提交创建表单时选中的选项。 As you can see I am trying to compare the id of the two and check the checkbox when the comparison returns true. 如您所见,我正在尝试比较两者的ID,并在比较结果为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: 我将修改maintainanceTypeList为每个项目添加一个附加属性,该属性显示是否应检查该项目:

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: 然后在单个* ngFor循环中显示maintainanceTypeList

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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