有没有一种方法可以将选中/选中的项目保存到数组中?

时间:2019-01-28 13:05:16

标签: arrays angular checkbox nativescript

我已经使用图像上的Checkbox插件完成了这样的网格, enter image description here

数据项已被标记为描述,已检查/未检查的布尔值,ID等等。

这是我的模板代码:

<StackLayout class="topbuttons">
<GridLayout columns="*,*" horizontalAlignment="left" verticalAlignment="top">
    <Button class="btn btn-primary topbutton" text="Next" col="1" (tap)="onTap()"></Button>
</GridLayout>

更多

<GridLayout tkExampleTitle tkToggleNavButton  class="topgrid" loaded="loaded" >
<RadListView [items]="dataItems" >
    <ng-template tkListItemTemplate let-item="item">
            <GridLayout class="garmentpick">
                <Image [src]="item.image" (tap)="toggleCheck()" class="imageP" >
                 </Image>
                <CheckBox #CB1 checked="false" text="{{ item.id }}" ></CheckBox>
        </GridLayout>
    </ng-template>
    <ListViewGridLayout tkListViewLayout ios:itemHeight="200" spanCount="2"></ListViewGridLayout>
</RadListView>

打字稿

 export const DATAITEMS: Array<DataItem> = [
{    id: 5451545, 
     name: "Chefs Collection",
     description: "This is item description.",
     image: "~/images/chefscollection.jpg",
     selected: false 
},
];

export class Component implements OnInit {
@ViewChild("CB1") firstCheckBox: ElementRef;

ngOnInit(): void {

    this._dataItems = new ObservableArray(this.getDataItems());
}
getDataItems(): Array<DataItem> {
    return DATAITEMS;
}
toggleCheck() {
    console.log();
    this.firstCheckBox.nativeElement.toggle();
}
onTap() {
    const checkboxArray = new ObservableArray(this.items);
    this._dataItems.forEach((item) => {
       checkboxArray.push(this.firstCheckBox.nativeElement.text);
    });        
}
}

我想将单击的项目保存到数组中。我创建了一个数组,我在提交按钮的ontap中将单击的项目推送到该数组,但是使用Array.push(item.id)仅推送一项,或者在该数组中重复它。有什么办法可以做到,我正在考虑数据表单

2 个答案:

答案 0 :(得分:2)

您的函数正在循环数组,使其始终推入相同的元素。您应该执行以下操作:

onTap() {
    const checkboxArray = new ObservableArray(this.items);
        this._dataItems.forEach((item) => {
        if(item.selected){
          checkboxArray.push(item);
        }
    });        
}

通过这种方式,您可以推送项目本身,而不是真正的本机元素。 如果要推送整个复选框,则应查看QuerySelector。 如果您要我进一步解释QuerySelector,请告诉我。

答案 1 :(得分:0)

也许,通过使用filter,如果我了解自己想要的东西,就可以实现自己想要的东西:

checkboxArray = this._dataItems.filter((item) => item.selected);
相关问题