我要選擇/取消選擇所有複選框。我試圖闖民宅其他代碼,但沒有什麼工作對我來說角2選擇/取消選擇所有複選框
下面是我的代碼。選擇unseleting特定單位正在爲我工作。基本上當我點擊div它選擇/取消選擇複選框,並添加顏色。但我很困惑與選擇所有/取消選擇所有
請幫我用我的代碼
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { ReactiveFormsModule, FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<form [formGroup]="form">
<div formArrayName="unitArr">
<label><input type="checkbox" />Select all</label>
<label><input type="checkbox" />unSelect all</label>
<div
*ngFor="let unit of units; let i = index"
class="unit"
(click)="onClick(i)"
[ngClass]="{'unit-selected': unitArr.controls[i].value}">
<input type="checkbox" formControlName="{{i}}"/>
<div class="unit-number">{{ unit.num }}</div>
<div class="unit-desc">{{ unit.desc }}</div>
</div>
</div>
</form>
`,
styles: [`.unit-selected { color: red; }`]
})
export class App implements OnInit{
private units = [
{num: 1, desc: 'Decription'},
{num: 2, desc: 'Decription'},
{num: 3, desc: 'Decription'},
];
private form: Form;
constructor (private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
unitArr: this.fb.array(
this.units.map((unit) => {
return this.fb.control(false); // Set all initial values to false
})
)
});
}
// Shorten for the template
get unitArr(): FormArray {
return this.form.get('unitArr') as FormArray;
}
onClick(i) {
const control = this.unitArr.controls[i];
control.setValue(!control.value); // Toggle checked
}
}
@NgModule({
imports: [ BrowserModule, ReactiveFormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
我猜你正在尋找的東西像[這](https://embed.plnkr.co/h9wFGz/) –
爲什麼不張貼此作爲回答,而不是評論,然後? – Graham
不要這樣寫:'formControlName = 「{{我}}」'但是這不是:'[formControlName] = 「我」' – ncohen