【发布时间】:2019-12-05 14:09:17
【问题描述】:
我正在尝试创建一个动态响应式表单。用户可以在文本(type = 1)输入或 img(type = 2)输入之间进行选择。根据他的选择,正在添加正确的输入。 - 他可以添加任意数量的输入字段。
我以前从未真正使用过反应形式,因此提出了这个问题。
下面的代码根据用户选择的模块添加了一个控件,但是例如添加一个textarea只显示一个带有[object Object]的textarea - 点击它会消失。
此外,我还没有弄清楚如何提交表单的输入。在提交时记录form返回表单,但没有文本区域的输入。
这就是我目前所拥有的:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div *ngFor="let module of form.get('modules').controls; let i = index" class="position-relative" [style.padding-bottom.rem]="paddingValue" (mouseover)="showPaddingInput = true" formArrayName="modules">
<div class="padding-input position-absolute d-flex justify-content-center" *ngIf="showPaddingInput === true" [style.height.rem]="paddingValue">
<input type="text" class="align-self-center text-center padding-input-field" [value]="paddingValue" (input)="changePadding(padding.value)" #padding>
</div>
<div class="text" *ngIf="module.value.type === 1">
<textarea class="flow-text" placeholder="Some Text..." rows="3" [formControlName]="i"></textarea>
</div>
<div class="img-container" *ngIf="module.value.type === 2">
<div class="custom-file align-self-center">
<input type="file" id="i" class="custom-file-input" [formControlName]="i" (change)="handleFileInput($event.target.files)">
<label class="custom-file-label" for="i"></label>
</div>
</div>
</div>
<button class="btn btn-dark">Submit</button>
</form>
export class CreateCaseCmsComponent implements OnInit {
form: FormGroup;
constructor(private caseService: CasesService) { }
addModule(type) {
if (type === 1) {
const control = new FormControl({type: 1}, Validators.required);
(this.form.get('modules') as FormArray).push(control);
} else if (type === 2) {
const control = new FormControl({type: 2}, Validators.required);
(this.form.get('modules') as FormArray).push(control);
}
}
ngOnInit() {
this.form = new FormGroup({
modules: new FormArray([])
});
}
onSubmit() {
console.log(this.form);
}
}
【问题讨论】:
标签: html angular typescript angular-reactive-forms