我正在尝试使用模板驱动的表单,将html中的模型绑定到新的 Person 实例。在为复选框创建到模型上的单个数组属性的适当绑定方面,我一直没有成功。
想法是数据将来自api或其他来源,并通过*ngFor
动态呈现复选框,并将所选内容绑定到 Person 模型属性,该属性将是数字数组。例如:
class Person {
firstName: string;
someCheckboxPropList: number[];
}
数据可能真的是任何东西
const dynamicData = [
{ name: 'name1', value: 1 },
{ name: 'name2', value: 2 }
];
如果要同时检查两个值和仅检查第二个值[ 1, 2 ]
,我的预期输出将类似于[ 2 ]
。
以下是PersonComponent.ts文件的外观示例
@Component({ ... })
export class PersonComponent {
submitted = false;
model = new Person();
constructor() { }
onSubmit(form) {
this.submitted = true;
console.log(form);
}
}
以及组件html文件所在的位置。
<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>
这不起作用(而且还是示例代码)。
答案 0 :(得分:1)
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]
So, make two functions
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
}
}
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.
When we have a person create a personForm,e.g.
this.service.getPerson().subscribe(person=>
{
this.personForm=createForm(person)
}
)
Our form
<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}}
And our sendData function
sendData(personForm)
{
console.log(this.retrieveData(personForm))
}
I make a simple stackblitz
Update
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
}
}
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))
}
答案 1 :(得分:1)
如果需要,我们可以制作一个自定义的Form控件。
在这种情况下,我们需要输入源和源的cols-第一个是键,第二个是显示的文本。
我做一个stackblitz
.html将是
<check-box-group name="props" [(ngModel)]="person.props"
[source]="dynamicData" cols="value,name" >
</check-box-group>
该组件是典型的自定义表单控件
@Component({
selector: 'check-box-group',
template: `
<div class="form-check" *ngFor="let item of source;let i=index">
<input class="form-check-input" id="{{_name+''+i}}"
type="checkBox" [ngModel]="_selectedItems[i]"
(ngModelChange)="setValue($event,i)">
<label class="form-check-label" for="{{_name+''+i}}">
{{item[_col]}}
</label>
</div>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckBoxGroupComponent),
multi: true
}
]
})
export class CheckBoxGroupComponent implements ControlValueAccessor {
@Input() source;
@Input()
set cols(value:string){ //cols is a string separated by commas
//e.g. "value,text", the "key" will be "value" and show the text
let _cols=value.split(',')
this._key = _cols[0];
this._col = _cols[1]
}
_selectedItems: any[] = [];
_key: string;
_col: string;
_name:string="";
onChange;
onTouched;
constructor(el:ElementRef) {
let name=el.nativeElement.getAttribute('name')
this._name=name?name:"ck";
}
writeValue(value: any[]): void {
this._selectedItems = this.propsToBoolean(value);
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
}
setValue(value: boolean, index: number) {
this._selectedItems[index] = value;
this.onChange(this.booleanToProps(this._selectedItems));
}
propsToBoolean(props): any[] {
console.log(props);
return props ? this.source.map((x: any) => props.indexOf(x[this._key]) >= 0)
: this.source.map(x => false);
}
booleanToProps(propsBoolean: boolean[]) {
let props: any[] = [];
if (propsBoolean) {
propsBoolean.forEach((item, index) => {
if (item)
props.push(this.source[index][this._key])
})
}
return props;
}
}
更新:添加验证
当我们有一个自定义表单组件并且想要进行“验证”时,我们有两个选择,即在组件外部进行验证或在组件内部进行验证。对于第二个选项,我们必须添加为提供者提供:NG_VALIDATORS,
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => CheckBoxGroupComponent),
multi: true,
}
并添加一个验证功能
validate(control: AbstractControl): ValidationErrors | null{
...your logic here.., e.g.
if (!this._selectedItems.find(x=>x))
return {error:"you must select one option at last"}
return null
}
嗯,还有更多要做的事情就是确定何时触摸我们的自定义控件。请记住,当控件失去焦点后会被触摸。我们可以在复选框的(模糊)中执行此操作(或将控件包含在带有tabindex = 0的div中)
<input type="checkbox" .... (blur)="onTouched()">
最后一步是使是否出错,这是我们向控件添加属性。我喜欢这样,如果我们添加一个属性isRequired,请检查错误,否则就不行。因此,我们添加了一个新属性_isRequired,并在构造函数中检查是否具有该属性
constructor(el:ElementRef) {
let name=el.nativeElement.getAttribute('name');
this._isRequired=el.nativeElement.getAttribute('isRequired')!=null?true:false;
this._name=name?name:"ck"; //<--this is necesary for give value to
//for="..." in label
}
我们的验证考虑了这一点
validate(control: AbstractControl): ValidationErrors | null{
if (!this._isRequired)
return null;
....
}
注意:我更新了自定义控件(并添加了一个属性[customClass])