角动态反应形式的问题

时间:2019-07-27 15:14:22

标签: html angular typescript angular-reactive-forms

我正在尝试创建动态的反应形式。用户可以在文本(类型= 1)输入或img(类型= 2)输入之间进行选择。根据他的选择,正在添加正确的输入。 -他可以根据需要添加任意多的输入字段。

我以前从没有真正使用过反应式,因此这个问题出现了。

下面的代码根据用户选择的模块添加了控件,但是例如,添加文本区域仅显示内部带有[object Object]的文本区域-单击使其消失。

此外,我还没有弄清楚如何提交表单的输入。在提交时登录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);
  }

}

1 个答案:

答案 0 :(得分:1)

表单控件的第一个参数是它的值,因此您将初始值设置为对象,这就是为什么它在文本框中显示[object Object]的原因...这就是调用.toString所得到的()在一个对象上,您需要像这样实例化它们:

const control = new FormControl('', Validators.required);

或类似的东西...这会影响您构建模板的方式,因此您可能需要更多类似的东西:

const group = new FormGroup({
   type: new FormControl(1),
   value: new FormControl('', Validators.required)
});

并将该组添加到您的阵列并按以下方式访问它:

  <div class="text" *ngIf="module.get('type').value === 1" [formGroupName]="i">
    <textarea class="flow-text" placeholder="Some Text..." rows="3" formControlName="value"></textarea>
  </div>