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


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

  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 => {


<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 *ngIf="field.type=='mat-select'">
      <mat-select formControlName="{{field.name}}">
        <mat-option *ngFor="let option of field.options" [value]="option">
  <br />

  <button mat-button (click)="Submit()" type="submit">Submit!</button>

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.