gpt4 book ai didi

javascript - Ionic 2动态添加表单字段

转载 作者:行者123 更新时间:2023-11-29 21:13:20 29 4
gpt4 key购买 nike

我想动态添加输入字段,这可能吗?有人有例子如何做到这一点?例如,当我从我的选择选项中选择 2 个输入字段时,它会显示我,而我选择 5 个输入字段时,它会显示 5 个输入字段

我想做那样的事

 <ion-item>
<ion-label fixed>Field 1</ion-label>
<ion-input type="text" value=""></ion-input>
</ion-item>

<ion-item *ngIf="someVariable === 'value1'">
<ion-label fixed>Field 2</ion-label>
<ion-input type="text" value=""></ion-input>
</ion-item>

</ion-list>
Then i bind select to someVariable:

<ion-item>
<ion-label>Options</ion-label>
<ion-select [(ngModel)]="someVariable">
<ion-option value="value1" selected="true">Option 1</ion-option>
<ion-option value="value2">Option 2</ion-option>
</ion-select>
</ion-item>

很好,但假设我有 8 个选项,如果用户选择选项 5,它会显示他的 5 个输入字段,我该怎么做?此外,如果我这样做,我需要动态声明变量,因为我需要将选项 5 值分配给特定变量。

最佳答案

其中一个选项是响应式

模板

<form [formGroup]="registerForm" class="form-horizontal">
<ion-item *ngFor="let item of fields" [ngClass]="{'has-error': registerForm.controls[item.id].errors}">
<ion-label fixed>{{item.key}}</ion-label>
<ion-input type="text" formControlName="{{item.key}}"></ion-input>
</ion-item>
</form>

<ion-item>
<ion-label>Options</ion-label>
<ion-select (change)="onFieldChange($event.target.value)">
<ion-option value="1" selected="true">Option 1</ion-option>
<ion-option value="2">Option 2</ion-option>
</ion-select>
</ion-item>

组件

import { Http, Headers } from "@angular/http";
import { ActivatedRoute } from "@angular/router";
import { Component } from "@angular/core";
import { FormGroup, Validators, FormBuilder } from '@angular/forms';

@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
fields = [];
registerForm: FormGroup = new FormGroup({});
constructor(private formBuilder: FormBuilder) {

}

onFieldChange(totalFields) {
var properties = [];
for (var i = 0; i < totalFields; i++) {
properties.push({ key: "field_" + i })
}
}

get value() {
//this will return form values as object
return this.registerForm.getRawValue();
}

setupForm(_properties) {
var formData = {};
_properties.forEach(element => {
var key = element.key;
formData[key] = ['default value if needed'];
//here you can write logic if you want fields to be required
if (true) {
formData[key].push(Validators.required);
}
});

this.registerForm = this.formBuilder.group(formData);
this.registerForm.valueChanges.subscribe(() => {
//if you wish here you can emit events when values changed in the form
});

this.fields = _properties;
}

title = "app works!";
}

关于javascript - Ionic 2动态添加表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40654527/

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