【发布时间】:2017-02-03 19:30:33
【问题描述】:
我有一个 Angular 2 组件,它在*ngFor 中加载并向用户显示复选框列表,该列表也可以基于键进行过滤。我需要选择所有过滤的项目并将它们添加到数组中。我可以检查所有复选框,但问题是当我更改checked 有问题时change 事件不会触发,知道如何解决这个问题吗?
模板:
<div class="form-group">
<input type="text" class="form-control" id="stringKeyFilter" placeholder="Key Filter"
[(ngModel)]="keyFilter">
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Id</th>
<th style="width: 150px;">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let device of devices| stringFilter: keyFilter">
<td>
{{device.$key}}
</td>
<td>
<div class="checkbox">
<label> <input type="checkbox"
[checked]="selectAll || selectedDevices.indexOf(device.$key) > -1"
(change)="updateSelectedDevices(device.$key, $event)" > View</label>
</div>
</td>
</tr>
</tbody>
</table>
<div class="btn-group pull-right">
<button type="button" class="btn btn-primary" (click)="selectAllDevices()">Select All</button>
<button type="button" class="btn btn-default" (click)="deselectAllDevices()">Deselect All
</button>
</div>
组件:
@Component({
moduleId: module.id,
selector: 'device-list',
template: template
})
export class DeviceListComponent implements OnInit {
devicesObservable: FirebaseListObservable<Device[]>;
devices: Device[] = [];
isLoading: boolean = true;
selectedDevices: string[] = [];
selectAll: boolean = false;
allCtrl: any;
keyFilter: string = '';
constructor(private af: AngularFire) {
}
ngOnInit(): void {
this.devicesObservable = this.af.database.list('/online', {
query: {
orderByKey: true,
}
});
this.devicesObservable.subscribe((devicesData)=> {
this.devices = devicesData;
this.isLoading = false
});
}
updateSelectedDevices(deviceId: string, event): void {
if (event.target.checked) {
this.selectedDevices.push(deviceId);
}
else {
_.pull(this.selectedDevices, deviceId);
}
}
loadingDeviceDetail(loading: boolean): void {
this.isLoading = loading;
}
selectAllDevices(): void {
this.selectAll = true;
}
deselectAllDevices(): void {
this.selectAll = false;
this.selectedDevices = [];
}
}
【问题讨论】:
-
你的问题不够清楚。你被困在哪里了?
-
问题是当我更改
checked有问题时,更改事件不会触发 -
您尚未将复选框与模型绑定。使用 ngModel 然后它应该会正常运行。