Angular 2多选框反应形式仅返回最后检查的值

时间:2017-08-31 12:10:44

标签: angular angular2-forms

我有以下代码

Template:

<div [formGroup]="booksFormGroup" class="btn-group" data-toggle="buttons">
    <ng-container *ngFor="let book of books">
        <label class="btn" [ngClass]="{'active': book.Id === selectedBookId}"
            (click)="bookClicked(book.Id)">
            <input type="checkbox" class="toggle" [value]="book.Id" formControlName="buttonsBook">{{book.Name}}
        </label>
    </ng-container>
</div>
<button (click)=onClicked()>Click</button>


TS file:

this.buttonsBook = new FormControl();
this.booksFormGroup = new FormGroup({
    buttonsBook: this.buttonsBook,
});

onClicked(){
    var selected = this.booksFormGroup.value.buttonsBook
}

当我点击按钮时,我只得到我检查的最后一个复选框的值,即使选中了多个。 我需要获取所有选中的复选框值。

我看到了一些解决方案,但它们不是基于反应形式,而是基于模板和反应的混合物,我并不喜欢。

2 个答案:

答案 0 :(得分:0)

您需要在html和ts中动态添加控件,例如关注

Template: I have added formControlName as book.Id here

<form [formGroup]="booksFormGroup" class="btn-group" data-toggle="buttons">
    <ng-container *ngFor="let book of books">
        <label class="btn" [ngClass]="{'active': book.Id === selectedBookId}"
            (click)="bookClicked(book.Id)">
            <input type="checkbox" class="toggle" [value]="book.Id" formControlName="book.Id">{{book.Name}}
        </label>
    </ng-container>
</form>
<button (click)=onClicked()>Click</button>

in TS:

Similary I have added control for each book inside ngOnInit

constructor( private fb: FormBuilder)
this.booksFormGroup = this.fb.group({
});

ngOnInit(): void {
this.books.forEach((book) =>{
this.booksFormGroup.addControl(book.id, new FormControl(''))
})
}
onClicked(){
    console.log(this.booksFormGroup.value);
}

答案 1 :(得分:-1)

问题是formControlName =“buttonsBook”对于所有行都是相同的。尝试为每一行绑定单个值。

尝试这样的事情:

<input type="checkbox" class="toggle" [value]="book.Id" formControlName={{book.Id}}>{{book.Name}}