0

我正在使用角度动态表单,填写表单后,我想将表单设置为查看模式(只读)。

html:

<dynamic-form [fields]="personal" (submit)="submit($event)"></dynamic-form>

零件:

@ViewChild(DynamicFormComponent) form: DynamicFormComponent;

 personal: FieldConfig[] = [
    {
      type: 'radiobutton',
      label: 'status',
      name: 'status',
      options: ['xxx', 'yyy', 'zzz'],
      value: 'xxx'
    },
    {
      type: 'select',
      label: 'Height',
      name: 'height',
      value: '',
      options: ['4.7', '4.8', '4.9', '5ft', '5.1', '5.2', '5.3', '5.4', '5.5', '5.6', '5.7', '5.8', '5.9', '6ft']
    },
    {
      type: 'input',
      label: 'Any',
      name: 'any'
    }
  ];

动态表单组件.ts

import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output
} from "@angular/core";
import {
  FormGroup,
  FormBuilder,
  Validators,
  FormControl
} from "@angular/forms";
import { FieldConfig, Validator } from "../../field.interface";

@Component({
  exportAs: "dynamicForm",
  selector: "dynamic-form",
  template: `
  <form class="dynamic-form" [formGroup]="form" (submit)="onSubmit($event)">
  <ng-container *ngFor="let field of fields;" dynamicField [field]="field" [group]="form">
  </ng-container>
  <button type="submit"  class="btn btn-primary">Save</button>
  </form>
  `,
  styles: []
})
export class DynamicFormComponent implements OnInit {
  @Input() fields: FieldConfig[] = [];

  @Output() submit: EventEmitter<any> = new EventEmitter<any>();

  form: FormGroup;

  get value() {
    return this.form.value;
  }
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.form = this.createControl();
  }

  onSubmit(event: Event) {
    event.preventDefault();
    event.stopPropagation();
    if (this.form.valid) {
      this.submit.emit(this.form.value);
    } else {
      this.validateAllFormFields(this.form);
    }
  }
}

我想到的一种方法是添加可以通过单击按钮启用保存的隐藏元素,但有没有更好的方法?我不知道。

4

0 回答 0