使用formbuilder动态添加字段

时间:2019-01-15 12:30:14

标签: angular forms angular2-formbuilder

enter image description here正在构建一个测验应用程序。“答案”选项的数量将是动态的。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.example">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:name=".QApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".article.ArticleActivity" android:theme="@style/AppTheme.NoActionBar.Light"/>

        <service
            android:name=".player.PlaybackService">
        </service>
    </application>
</manifest>

如何添加动态选项并与ui绑定?

1 个答案:

答案 0 :(得分:0)

我使用FormArray []做过类似的事情。

在我的ts中:

//声明数组

answerOptions: FormArray = new FormArray([]);

//初始化

createForm() {
        this.quizForm = new FormGroup({
            answerOptions: this.formBuilder.array([])
        });
    }

//根据需要添加

addAnswerOptionControl(option: AnswerOption): void {
        this.answerOptions = this.quizForm.get('answerOptions') as FormArray;
        this.answerOptions.push(this.createOptionControl(option));
    }


createOptionControl(option: AnswerOption)): FormGroup {
    return this.formBuilder.group({
        option: new FormControl('', Validators...]
        )
    });
}

get formData() {
    return <FormArray>this.quizForm.get('answerOptions');
}

在我看来:

<div formArrayName="answerOptions" *ngFor="let option of formData.controls; let i = index">
                <div [formGroupName]="i">
                    <mat-form-field>
                        <input
                            type="text"
                            formControlName="answerOption"
                        />
                    </mat-form-field>
                </div>
            </div>