如何在angular2中选择for循环中的多个复选框?

时间:2017-04-01 10:24:32

标签: angular

我已经尝试使用带有复选框的角度2来列出类别列表,用户可以选择任何类别。我试过下面的代码。问题是,如果我选中任何一个复选框,则选中所有复选框,并且我无法在保存功能上获取表单值。 Food.category是动态的。我该如何解决这个问题?

<form #f="ngForm" novalidate>
    <div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;">
        <label for="categoryname">          
            <input type = "checkbox" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}
        </label>
    </div>  
    <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
</form> 

export class ExploreListComponent implements OnInit {
    Catcheckbox:true ;

    onClick(categoryname) {
        alert(categoryname + ' was clicked!');
    }

    save(isValid: boolean, f: User) {
        if (!isValid) return;
        console.log(f);
    }
}

3 个答案:

答案 0 :(得分:1)

如下所示更改您的代码,您将获得所有选中的复选框值;

模板:

<form #f="ngForm" novalidate>
    <div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;let i=index;">
        <label for="categoryname">          
            <input type="checkbox" name="categoryname[{{i}}]"  [value]="categoryname" 
(change)="categories[$event.target.getAttribute('value')]=$event.target.checked"/>
        {{categoryname}}
        </label>
    </div>  
        <button type="submit" (click)="save(f.valid)" class="btn btn-default">Submit</button>
</form> 

组件:

export class ExploreListComponent implements OnInit {

        categories = {};

        save(isValid: boolean) {
            if (!isValid) return;
            console.log(this.categories);
        }
    }

答案 1 :(得分:0)

<div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;">
            <label for="categoryname">          
             <input type = "checkbox" *ngIf="selectAll" [checked]="selectedAll" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>


               <input type = "checkbox" *ngIf="selectAll" [checked]="!selectedAll" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}
            </label>
        </div>  
         <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
    </form> 

点击全选按钮

this.selectAll=true

因此选择了所有元素,并将整个数组传递给* ngFor

答案 2 :(得分:0)

我建议使用ReactiveFormsModule。在这种情况下,您将数组分配给所有输入名称属性。尝试仅分配在* ngFor指令

中设置的当前索引,如name =“{{i}}”
var getData = function(callback) {
    $.getJSON('api/someurl').done(function (data) {
        var results = $("#Mydropdown")
            .empty()
            .append("<option value=''>Please select</option>");

        // loop data and build list

        // after you have built the new list invoke the callback
        callback();
    })
    .fail(function (jqXHR, textStatus, err) {
    });
};