Получить значение формы при отправке формы в Angular 8 - PullRequest
0 голосов
/ 07 мая 2020

Я искал inte rnet, чтобы построить форму Dynami c. форма работает нормально, но я не могу получить входное значение при отправке формы. Ниже мой код:

Service textbox.ts

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
    selector: 'fieldinput',
    template: `
      <div [formGroup]="form">
          <input *ngIf="!field.multiline" [attr.type]="field.type" class="form-control"  [id]="field.name" [name]="field.name" [formControlName]="field.name">
      </div> 
`
})
export class TextBoxComponent {
@Input() field:any = {};
@Input() form:FormGroup;
get isValid() { return this.form.controls[this.field.name].valid; }
get isDirty() { return this.form.controls[this.field.name].dirty; }

    constructor() {

    }
}

field Builder field-builder.component.ts

import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'field-builder',
template: `
  <div class="form-group row" [formGroup]="form">
    <label class="col-md-3 form-control-label" [attr.for]="field.label">
      {{field.label}}
      <strong class="text-danger" *ngIf="field.required">*</strong>
   </label>
   <div class="col-md-9" [ngSwitch]="field.type">
     <fieldinput *ngSwitchCase="'text'" [field]="field" [form]="form"></fieldinput>
     <dropdown *ngSwitchCase="'dropdown'" [field]="field" [form]="form"></dropdown>
     <checkbox *ngSwitchCase="'checkbox'" [field]="field" [form]="form"></checkbox>
     <radio *ngSwitchCase="'radio'" [field]="field" [form]="form"></radio>
     <file *ngSwitchCase="'file'" [field]="field" [form]="form"></file>
     <div class="alert alert-danger my-1 p-2 fadeInDown animated" *ngIf="!isValid && isDirty">{{field.label}} is required</div>
   </div>
 </div>
`
})
export class FieldBuilderComponent implements OnInit {
  @Input() field:any;
  @Input() form:any;

  get isValid() { return this.form.controls[this.field.name].valid; }
  get isDirty() { return this.form.controls[this.field.name].dirty; }

  constructor() { }

  ngOnInit() {
  }
}

form builder Dynami c -form -builder.component.ts

import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
  selector: 'dynamic-form-builder',
  template:`    
    <div *ngFor="let field of fields">
       <field-builder [field]="field" [form]="form"></field-builder>
    </div>
    <div class="form-row"></div>
    <div class="form-group row">
      <div class="col-md-3"></div>
      <div class="col-md-9">
        <button type="submit" [disabled]="!form.valid" class="btn btn-primary">Save</button>
        <strong >Saved all values</strong>
      </div>
    </div>
  `,
})
export class DynamicFormBuilderComponent implements OnInit {
@Output() onSubmit = new EventEmitter();  
@Input() fields: any[] = [];
form: FormGroup;
constructor() { }

ngOnInit() {
  let fieldsCtrls = {};
  for (let f of this.fields) {
    if (f.type != 'checkbox') {
      fieldsCtrls[f.name] = new FormControl(f.value || '', Validators.required)
    } else {
      let opts = {};
      for (let opt of f.options) {
        opts[opt.key] = new FormControl(opt.value);
      }
      fieldsCtrls[f.name] = new FormGroup(opts)
    }
  }
  this.form = new FormGroup(fieldsCtrls);
 }

}

app.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public form: FormGroup;
  unsubcribe: any;
  firstName: string;

  public fields: any[] = [
    {
      type: 'text',
      name: 'firstName',
      label: 'First Name',
      value: ''
    },
    {
      type: 'text',
      name: 'lastName',
      label: 'Last Name',
      value: '',
    },
    {
      type: 'text',
      name: 'email',
      label: 'Email',
      value: '',
      required: true,
    },
    {
      type: 'dropdown',
      name: 'country',
      label: 'Country',
      value: 'in',
      required: true,
      options: [
        { key: 'in', label: 'India' },
        { key: 'us', label: 'USA' }
      ]
    },
    {
      type: 'radio',
      name: 'country',
      label: 'Country',
      value: 'in',
      required: true,
      options: [
        { key: 'm', label: 'Male' },
        { key: 'f', label: 'Female' }
      ]
    },
    {
      type: 'checkbox',
      name: 'hobby',
      label: 'Hobby',
      required: true,
      options: [
        { key: 'f', label: 'Fishing' },
        { key: 'c', label: 'Cooking' }
      ]
    }
  ];

  constructor() {

    this.form = new FormGroup({
      fields: new FormControl(JSON.stringify(this.fields))
    })
    this.unsubcribe = this.form.valueChanges.subscribe((update) => {
      this.fields = JSON.parse(update.fields);
    });
  }

  onUpload(e) {
    console.log(e);
  }
  onSubmit(){
    alert(JSON.stringify(this.form.value))
  }
  ngDistroy() {
    this.unsubcribe();
  }
}

app.component. html

<div class="col-sm-12">
  <div class="card">
    <div class="card-header">Dynamic Forms</div>
    <div class="card-body">
        <form (ngSubmit)="onSubmit()" [formGroup]="form" class="form-horizontal">
            <dynamic-form-builder [fields]="fields"></dynamic-form-builder>
        </form>
    </div>
  </div>
</div>

<div class="col-sm-12">
    <div class="form-group" [formGroup]="form">
        <label>JSON</label>
        <textarea formControlName="fields" class="form-control" rows="3"></textarea>

    </div>
</div>

При отправке формы я не могу получить входное значение. Ниже представлен результат отправки формы.

{"fields":"[{\"type\":\"text\",\"name\":\"firstName\",\"label\":\"First Name\",\"value\":\"\"},{\"type\":\"text\",\"name\":\"lastName\",\"label\":\"Last Name\",\"value\":\"\"},{\"type\":\"text\",\"name\":\"email\",\"label\":\"Email\",\"value\":\"\",\"required\":true},{\"type\":\"dropdown\",\"name\":\"country\",\"label\":\"Country\",\"value\":\"in\",\"required\":true,\"options\":[{\"key\":\"in\",\"label\":\"India\"},{\"key\":\"us\",\"label\":\"USA\"}]},{\"type\":\"radio\",\"name\":\"country\",\"label\":\"Country\",\"value\":\"in\",\"required\":true,\"options\":[{\"key\":\"m\",\"label\":\"Male\"},{\"key\":\"f\",\"label\":\"Female\"}]},{\"type\":\"checkbox\",\"name\":\"hobby\",\"label\...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...