簡體   English   中英

用戶輸入角度為 6 的動態反應形式

[英]Dynamic reactive forms with user input in angular 6

如何根據輸入表單用戶(下拉選擇)添加表單字段,它可以在角度反應形式中具有輸入、按鈕、復選框等。

您基本上可以從下拉列表中檢查所選選項的值,並根據使用 *ngIf 顯示其他字段或不顯示其他字段

我認為這就是您所要求的......不是使用下拉選擇而是動態地向表單添加字段。

請參閱以下示例。 https://angular-vfeusd.stackblitz.io

app.component.ts

 import { Component } from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular'; form: FormGroup; newFieldName: string; controlNames: string[] = []; pageMessage = ""; constructor(private fb:FormBuilder){ this.form = fb.group({}) } addToForm(event){ console.log(this.newFieldName); const ctrl = new FormControl(); ctrl.validator = Validators.required; ctrl.setValue(null); this.form.addControl(this.newFieldName, ctrl) this.controlNames.push(this.newFieldName); this.newFieldName = ''; } submitForm(){ if(!this.form.valid){ this.pageMessage = "invalid form" } this.pageMessage = ''; console.log(this.form.value) } } app.component.ts
 <hello name="{{ name }}"></hello> <p> Start editing to see some magic happen :) </p> Enter input name: <input type="text" name="formfieldname" [(ngModel)]="newFieldName"> <button type="button" name="enterButton" (click)="addToForm($event)">Enter</button> <hr> {{pageMessage}} <form [formGroup]="form"> <table> <tr *ngFor="let c of controlNames; let x=index"> <td>{{c}}</td> <td><input type="text" name="{{c}}" value="" placeholder="enter value" [formControlName]="c"> </td> </tr> </table> <button type="button" name="formsubmit" (click)="submitForm()">Submit Form</button> </form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM