如何将检查后的值放入Angular模板驱动形式(ngModel)的数组中 [英] How to get checked values into an array for Angular Template Driven Form (ngModel)
问题描述
我正在尝试使用模板驱动的表单,将html中的模型绑定到新的 Person 实例.我一直未能为复选框创建到模型上单个数组属性的正确绑定.
I'm attempting to use template driven forms, binding to a model in the html to a new instance of lets say Person. I've been unsuccessful in creating a proper binding for checkboxes to a single array property on my model.
想法是数据将来自api或其他来源,通过*ngFor
动态呈现复选框,并将所选内容绑定到 Person 模型属性,该属性将是数字数组.例如:
The idea is data will come from an api or other source, dynamically render checkboxes via *ngFor
and bind what is selected to the Person models property which would be an array of numbers. For example:
class Person {
firstName: string;
someCheckboxPropList: number[];
}
数据可能真的是任何东西
and data could be anything really
const dynamicData = [
{ name: 'name1', value: 1 },
{ name: 'name2', value: 2 }
];
如果要同时检查两个值和仅检查第二个值,我的预期输出将是[ 1, 2 ]
的东西.
my expected output would be something along the lines of [ 1, 2 ]
if both values where to be checked and if only the second was checked [ 2 ]
.
以下是PersonComponent.ts文件的外观示例
Here's a sample of what the PersonComponent.ts file might look like
@Component({ ... })
export class PersonComponent {
submitted = false;
model = new Person();
constructor() { }
onSubmit(form) {
this.submitted = true;
console.log(form);
}
}
以及组件html文件所在的位置.
And where I'm at with the components html file.
<form (ngSubmit)="onSubmit(form)" #form="ngForm">
<input type="text" [(ngModel)] name="person.firstName">
<div *ngFor="let dataItem of dynamicData" >
<input
type="checkbox"
ngModel
name="dynamicData"
[value]="dataItem.value">
<label>{{dataItem.name}}</label>
</div>
</form>
这不起作用(而且还是示例代码).
This does not work (and is sample code anyway).
推荐答案
这个想法有两件事:Person和PersonForm,例如,
the idea is have two things: Person and PersonForm, so,e.g
person={firstName:"Jessy",props:[1,2]
//but
personForm={firstName:"Jessy",props:[true,true]
所以,要实现两个功能
createForm(person) {
return {
firstName: person.firstName,
props: this.dynamicData.map(x => person.props.indexOf(x.value) >= 0)
}
}
retrieveData(personForm) {
let props: number[] = [];
personForm.props.forEach((v, index) => {
if (v)
props.push(this.dynamicData[index].value)
}
)
return {
firstName: personForm.firstName,
props: props
}
}
好吧,我们已经拥有了所有需要的东西.当我们收到一个人时,创建一个personForm,它就是我们在表单中更改的数据.在提交中,只需调用retrieveData即可获得人员的价值.
Well, we have already all we need. When we received a person, create a personForm that it's the data we change in the form. In submit simply call to retrieveData to get the value of person.
当我们有一个人时,创建一个personForm,例如
When we have a person create a personForm,e.g.
this.service.getPerson().subscribe(person=>
{
this.personForm=createForm(person)
}
)
我们的表格
<form *ngIf="personForm" (submit)="sendData(personForm)">
<input name="firtName" [(ngModel)]="personForm.firstName">
<div *ngFor="let item of dynamicData;let i=index">
<input name="{{'prop'+i}}"
type="checkBox" [(ngModel)]="personForm.props[i]">{{item.name}}
</div>
<button>Submit</button>
</form>
{{personForm|json}}<br/>
{{retrieveData(personForm)|json}}
还有我们的sendData函数
And our sendData function
sendData(personForm)
{
console.log(this.retrieveData(personForm))
}
我制作了简单的stackblitz
更新
注意:我们可以使用spred运算符来设置属性,因此
NOTE:We can use the spred operator to asing properties, so
createForm(person) {
return {
...person, //All the properties of person, but
props: this.dynamicData.map(x => person.props.indexOf(x.value) >= 0)
}
}
retrieveData(personForm) {
let props: number[] = [];
personForm.props.forEach((v, index) => {
if (v)
props.push(this.dynamicData[index].value)
}
)
return {
..personForm, //all the properties of personForm, but
props: props
}
}
注意2:在现实世界"中,人员来自服务.考虑一下服务获取/接收"personForm"的想法,然后将要转换的功能放入服务中
NOTE2: In a "real world" the persons goes from a service. Consider the idea that service get/received the "personForm" and put the functions to transform in the service
//in service
getPerson()
{
return this.httpClient.get("...").map(res=>this.createForm(res))
}
savePerson(personForm)
{
return this.httpClient.post("...",this.retrieveData(personForm))
}
这篇关于如何将检查后的值放入Angular模板驱动形式(ngModel)的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!