0
私はバックエンドから得ている興味のリストを持っています。私は、ユーザーが彼らが望む興味を選択できるようにしたい。チェックした利息のみをDBに保存し、ページを読み込むときにあらかじめ入力します。しかし、まず、ユーザーが選択したこれらの関心事を取得する必要があります。角度+マテリアル - フォームグループで複数のチェックボックスを処理する方法
interest.component.ts
export class InterestsComponent implements OnInit {
interestFormGroup : FormGroup
interests:any;
selected: any;
constructor(public interestService: InterestService, private formBuilder: FormBuilder,
) { }
ngOnInit() {
this.interestFormGroup = this.formBuilder.group({
interests: this.formBuilder.array([])
});
this.interestService.all().subscribe((res) => {
this.interests = res;
});
}
change() {
console.log(this.interestFormGroup.value);
}
}
変更イベントで私はconsole.logでinterest.component.html
<div id="interest">
<div class="interest-list">
<form [formGroup]="interestFormGroup">
<div *ngFor="let interest of interests" >
<mat-checkbox class="example-margin" formNameArray="interests" (change)="change()">{{interest}}</mat-checkbox>
</div>
</form>
</div>
</div>
それはそこに示しては、内の関心のアレイに追加されているいかなる値ではありませんinterestFormGroupチェックボックスもチェックされています。次のようにテンプレートを変更
this.interests = res;
const formArray = this.interestFormGroup.get('interests') as FormArray;
this.interests.forEach(x => formArray.push(new FormControl(false)));
:
<form [formGroup]="interestFormGroup" (ngSubmit)="submit()">
<ng-container formArrayName="interests">
<div *ngFor="let interest of interests; let i = index" >
<mat-checkbox class="example-margin" [formControlName]="i">
{{interest}}
</mat-checkbox>
</div>
</ng-container>
<button>Submit</button>
</form>
そして、あなたはあなたにFormArray
値を変換する必要があるフォームを送信しますが
stackblitzから、私が欲しいものではないthatsの、それは本当の配列を返し、私が実際に興味のある値を望むとき、偽の値。真と偽の値は実際にはキーがインデックスであるためにどのような関心が選択されたかを教えてくれません。私はなぜインデックスがここに追加されているのか分からないのですか?シンプルなものを意味する複雑な解決策のように思えます。 –
そのstackbltizの例では、interest1、interest2、interest3ではない値の配列を返す必要があります。true:1:true 2:true –
フォームを送信しようとしましたか?コンソールを見て – yurzui