在Angular 6中,可以使用ngModel指令和ngFor指令来实现在循环中将所有复选框都设置为选中状态。
首先,在组件中定义一个布尔类型的变量来表示复选框的选中状态:
selectedAll: boolean = false;
然后,在模板中使用ngFor指令来循环生成复选框,并使用ngModel指令将复选框与selectedAll变量进行绑定:
{{ item }}
接下来,实现一个方法来处理选中所有复选框的逻辑:
selectAll() {
for(let item of this.items) {
item.isSelected = this.selectedAll;
}
}
最后,在模板中添加一个按钮,并调用selectAll方法来选中所有复选框:
完整的示例代码如下:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
{{ item }}
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
items: string[] = ['Item 1', 'Item 2', 'Item 3'];
selectedAll: boolean = false;
selectAll() {
for(let item of this.items) {
item.isSelected = this.selectedAll;
}
}
}
这样,当点击"Select All"按钮时,所有的复选框都会被选中或取消选中。