gpt4 book ai didi

html - 如何将选定复选框的值作为数组发送到函数?

转载 作者:行者123 更新时间:2023-12-02 03:17:41 25 4
gpt4 key购买 nike

我对使用 Angular 相当陌生,想知道是否有一种简单的方法来首先检查复选框是否被选中。如果选择了它,我想将其传递给 saveOptions 函数。如果选择了多个,我想将它们全部传递并将它们保存到一系列选项中。有人可以帮我吗?

import { Component } from '@angular/core';
import { forEach } from '@angular/router/src/utils/collection';
import { Options } from 'selenium-webdriver/ie';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
options: any = []



saveOptions(x:any[]){
x.forEach(element => {
this.options.push(element);
});
}

}
<ul class="option-row">
<div class="option-group">
<li><input type="checkbox" id="option-1" value="1" required> <label for="option-1">Option 1</label></li>
<li><input type="checkbox" id="option-2" value="2" required> <label for="option-2">Option 2</label></li>
<li><input type="checkbox" id="option-3" value="3" required> <label for="option-3">Option 3</label></li>
</div>
<!--Want to know how to check if the checkbox is selected and pass the selected options to the method-->
<button type="button" (click)="saveOptions();">Submit</button>
</ul>

最佳答案

一种方法是订阅表单的 valueChanges,如下所示:

export class AppComponent implements OnInit {
options: any = []
model = { optionOne: false, optionTwo: false, optionThree: false }
formChangesSubscription;
@ViewChild('form') ngForm: NgForm;

ngOnInit() {
this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(x => {
console.log(x);
})
}

saveOptions(x: any[]) {
x.forEach(element => {
this.options.push(element);
});
}
}
<form #form="ngForm">
<ul class="option-row">
<div class="option-group">
<li><input type="checkbox" [(ngModel)]="model.optionOne" name="optionOne" id="option-1" value="1" required> <label for="option-1">Option 1</label></li>
<li><input type="checkbox" [(ngModel)]="model.optionTwo" name="optionTwo" id="option-2" value="2" required> <label for="option-2">Option 2</label></li>
<li><input type="checkbox" [(ngModel)]="model.optionThree" name="optionThree" id="option-3" value="3" required> <label for="option-3">Option 3</label></li>
</div>
<!--Want to know how to check if the checkbox is selected and pass the selected options to the method-->
<button type="button" (click)="saveOptions();">Submit</button>
</ul>
</form>

https://stackblitz.com/edit/angular-j5idkn?file=src%2Fapp%2Fapp.component.ts

关于html - 如何将选定复选框的值作为数组发送到函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55636699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com