1
\$\begingroup\$

How can I improve this code? Is it somehow possible to remove fields from HTML and pass all necessary data through FormGroup?

app.components.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  myForm: FormGroup;

  fields = [
    { label: "Drill Bit Type", name: "drillBitType", options: ["Masonry", "SDS", "Universal"], type: "mat-input" },
    { label: "Drill Bit SharpAngel", name: "drillBitSharpAngel", options: ["118", "120", "135"], type: "mat-select" },
    { label: "Drill Bit Sharp Direction", name: "drillBitSharpDirection", options: ["Left", "Right"], type: "mat-select" }];

  constructor(private formBuilder: FormBuilder) {
    let dictionary: { [key: string]: FormControl; } = {};
    this.fields.forEach(element => {
      dictionary[element.name] = new FormControl(element.label);
    });
    this.myForm = new FormGroup(dictionary);
  }

  Submit() {
    this.fields.forEach(element => {
      console.log(this.myForm.value[element.name]);
    });
  }
}

app.components.html

<br />
<form [formGroup]="myForm">
  <ng-container *ngFor="let field of fields">
    <br />
    <mat-form-field class="example-full-width" *ngIf="field.type=='mat-input'">
      <input matInput formControlName="{{field.name}}">
    </mat-form-field>

    <mat-form-field *ngIf="field.type=='mat-select'">
      <mat-label>{{field.label}}</mat-label>
      <mat-select formControlName="{{field.name}}">
        <mat-option *ngFor="let option of field.options" [value]="option">
          {{option}}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </ng-container>
  <br />

  <button mat-button (click)="Submit()" type="submit">Submit!</button>
</form>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.