每次尝试保存所选项目后,我都希望清除该列表或清空。例如,用户选择了一个项目 - 选择保存。在控制台中,您将查看已选择的对象。现在,如果您选择其他项目并选择保存,您仍将看到在控制台中选择的上一个项目。最好是在每次保存后,阵列都被清除。
首先保存:
selectedMessages
Array(1)
{messageID: 222, message: "text"}
第二次保存:
selectedMessages
Array(2)
{messageID: 222, message: "text"}
{messageID: 331, message: "text Two"}
component.ts
rMessages: Message[] = [];
aMessages: Message[] = [];
constructor(
public formBuilder: FormBuilder,
) {
this.messageForm = formBuilder.group({
selectedMessages: this.formBuilder.array([])
})
}
save(form){
console.log(form.value.selectedMessages)
}
select(rmessage:Message, isChecked: boolean){
const selectedMessages = <FormArray>this.messageForm.controls.selectedMessages;
if(isChecked) {
selectedMessages.push(new FormControl(rmessage));
} else {
let index = selectedMessages.controls.findIndex(x => x.value.messageID == rmessage.messageID);
selectedMessages.removeAt(index);
}
}
buildChecked() {
const arr = this.rMessages.map(message => {
console.log(this.formBuilder.control(message.messageID))
return this.formBuilder.control(message.messageID)
});
return this.formBuilder.array(arr);
}
HTML
<form [formGroup]="messageForm" (ngSubmit)="save(messageForm)">
<ion-list active text-wrap *ngSwitchCase="'received'" >
<div class="items">
<ion-item *ngFor="let rmessage of rMessages; index as i">
<ion-label>
{{rmessage.message}}
</ion-label>
<ion-checkbox (ionChange)="select(rmessage, $event.checked)" value="rmessage"></ion-checkbox>
</ion-item>
</div>
<button ion-button full type="submit" style="font-size:1.8rem">save</button>
</ion-list>
</form>
答案 0 :(得分:0)
要清除表单,您需要:
selectedMessages.reset()
我不太清楚messageForm的结构是否可以访问selectedMessages,但是console.log会帮助你。