Is there a way to display an array of data in separate mat-form-field components?

I am dealing with an array that stores 4 data points: [onHour, onMinute, offHour, offMinute]. I also have 4 elements that are not in an array and need to be repeated.


        <div class="on">
            <mat-form-field appearance="fill" class="time_field">
                <mat-label>minute</mat-label>
                <input matInput type="number" formControlName="minute_glow_periodic" min="0" max="59">
            </mat-form-field>
            <mat-form-field appearance="fill" class="time_field">
                <mat-label>hour</mat-label>
                <input matInput type="number" formControlName="hour_glow_periodic" min="0" max="24">
            </mat-form-field>
        </div>

        <div class="off">
            <mat-form-field appearance="fill" class="time_field">
                <mat-label>minute</mat-label>
                <input matInput type="number" formControlName="minute_glow_periodic" min="0" max="59">
            </mat-form-field>
            <mat-form-field appearance="fill" class="time_field">
                <mat-label>hour</mat-label>
                <input matInput type="number" formControlName="hour_glow_periodic" min="0" max="24">
            </mat-form-field>
        </div>
    

Within the .ts component, I have a variable

periodicValues = [this.hourGlowPeriodic?.value, this.minuteGlowPeriodic?.value, this.hourSilencePeriodic?.value, this.minuteSilencePeriodic?.value];
that populates the interface upon submit button click. However, I am unsure of how to fill the form control with the periodicValues[] array in the ngOnInit lifecycle hook.

I attempted to use this code snippet, but it did not work as expected:


        this.form = this.formBuilder.group({
            hour_glow_periodic: new UntypedFormControl({ value: this.data.element?.periodic_values[0], disabled: false }),
            minute_glow_periodic: new UntypedFormControl({ value: this.data.element?.periodic_values[1], disabled: false }),
            hour_silence_periodic: new UntypedFormControl({ value: this.data.element?.periodic_values[2], disabled: false }),
            minute_silence_periodic: new UntypedFormControl({ value: this.data.element?.periodic_values[3], disabled: false }),
        });
    

Answer №1

To enhance your HTML code, consider updating the last two instances of formControlName with the values hour_silence_periodic and minute_silence_periodic. Your current code appears to be correct based on the provided data. Below is a sample working example. Kindly let me know if you encounter any issues.

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
} from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { provideAnimations } from '@angular/platform-browser/animations';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    CommonModule,
    MatFormFieldModule,
    MatInputModule,
    MatIconModule,
  ],
  template: `
 <form [formGroup]="form">
    <div class="on">
       <mat-form-field appearance="fill" class="time_field">
          <mat-label>minute</mat-label>
          <input matInput type="number" formControlName="minute_glow_periodic" min="0" max="59">
       </mat-form-field>
       <mat-form-field appearance="fill" class="time_field">
          <mat-label>hour</mat-label>
          <input matInput type="number" formControlName="hour_glow_periodic" min="0" max="24">
       </mat-form-field>
    </div>
    <div class="off">
       <mat-form-field appearance="fill" class="time_field">
          <mat-label>minute</mat-label>
          <input matInput type="number" formControlName="hour_silence_periodic" min="0" max="59">
       </mat-form-field>
       <mat-form-field appearance="fill" class="time_field">
          <mat-label>hour</mat-label>
          <input matInput type="number" formControlName="minute_silence_periodic" min="0" max="24">
       </mat-form-field>
    </div>
 </form>
  `,
})
export class App {
  name = 'Angular';
  data = {
    element: {
      periodic_values: [1, 2, 3, 4],
    },
  };
  form: FormGroup = new FormGroup({});

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.form = this.formBuilder.group({
      hour_glow_periodic: new FormControl({
        value: this.data.element?.periodic_values[0],
        disabled: false,
      }),
      minute_glow_periodic: new FormControl({
        value: this.data.element?.periodic_values[1],
        disabled: false,
      }),
      hour_silence_periodic: new FormControl({
        value: this.data.element?.periodic_values[2],
        disabled: false,
      }),
      minute_silence_periodic: new FormControl({
        value: this.data.element?.periodic_values[3],
        disabled: false,
      }),
    });
  }
}

bootstrapApplication(App, {
  providers: [provideAnimations()],
});

stackblitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing Ionic's functionality by including extra access control to permit origin in response headers

Dealing with the issue of Ionic/Angular adding extra access control allow origin to response headers. How can this be prevented? My Nginx server currently has CORS enabled add_header 'Access-Control-Allow-Origin' '*' always; add_header ...

Encountering "Object is possibly undefined" during NextJS Typescript build process - troubleshooting nextjs build

I recently started working with TypeScript and encountered a problem during nextjs build. While the code runs smoothly in my browser, executing nextjs build results in the error shown below. I attempted various solutions found online but none have worked s ...

(NG2-CHARTS) Unable to connect to the Chart Type as it is not recognized as a valid property for binding

I encountered an issue with my Chart Component where I am seeing the error message below. I have successfully imported ChartsModule into my app.module.ts file, but I am unsure why this error is occurring? Can't bind to 'ChartType' since ...

Tips for Achieving Observable Synchronization

I've encountered a coding challenge that has led me to this code snippet: ngOnInit(): void { this.categories = this.categoryService.getCategories(); var example = this.categories.flatMap((categor) => categor.map((categories) = ...

Receiving API response with a format similar to JSON, but encountering an issue during the parsing process

My API is returning the following: {"permissions": [{"id":1,"product_id":10,"permission_type":"ADD","name":"Add"}, {"id":2,"product_id":10,"p ...

Error: Navbar component cannot access static member

I am encountering the error message Static member is not accessible at this particular point: auth.service.ts export class AuthService { public static get isLoggedIn() { const user = JSON.parse(localStorage.getItem('user')); return (u ...

I am looking to superimpose one rectangle over another rectangle

I am looking to create something similar using CSS and TypeScript/JavaScript: Could someone please guide me on how to achieve this? My attempt with a flex container looks like this: I am new to front-end development. Can anyone point out what I might be ...

creating a new date instance with a specific time zone

Creating a Date object with a dynamically selected timezone is my current goal while I am located in the IST time zone. To avoid the unpredictable behavior of Date.parse(), I am looking for an alternative method. Let's say we set the tzOffset to +05:3 ...

Creating multilingual menus with ABP and Nebular

Currently, I am in the process of developing an application using ABP framework version 4.4 and integrating the Nebular theme as opposed to the default basic theme. Amidst various challenges faced during this migration, one particular issue stands out - lo ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Refresh the page using a promise in Angular after a delay of 3 seconds

Currently, I am working on enhancing the functionality of the login page. In case a user enters an incorrect login and password combination, my goal is to have the page automatically reload after 3 seconds. Despite my best efforts, I have encountered chall ...

Hello everyone, I'm encountering problems while trying to retrieve data from

I've been experimenting with the ngrx store, but I'm encountering some difficulties: Mainly, I'm having trouble fetching information from the store. You can find my code here: https://github.com/FabioBiao/ngrxtTest In the home.component.t ...

Navigating in Angular 4 using the `router.navigate`

After implementing a login feature in my application's LoginComponent, I encountered an issue. Within the LoginComponent.ts file: onSubmit(loginForm: NgForm): void { if(loginForm.valid) { this.authService.login(loginForm.value) ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

An effective way to define the type of a string property in a React component using Typescript

One of the challenges I'm facing is related to a React component that acts as an abstraction for text fields. <TextField label="Enter your user name" dataSource={vm} propertyName="username" disabled={vm.isSaving} /> In this set ...

Ways to extract the body/message of a request from an HttpErrorResponse in Angular using the ErrorHandler

Imagine I make a request to the server using the post method in order to create a new user. In case the server responds with an error, my goal is to retrieve the form data that was submitted along with that request from the ErrorHandler. This information i ...

Error in InversifyJs exclusively occurring in Internet Explorer

I'm currently utilizing Typescript with webpack for the development of a web application. Recently, I made the transition to using the inversifyJs DI library. However, I am encountering a specific error only when testing on Internet Explorer (version ...

Using the TypeScript NextPage function along with the getInitialProps static method and @typescript-eslint/unbound-method

After enabling typescript-eslint with its recommended settings, I encountered an issue in my code. I came across this helpful post on Stack Overflow: Using getInitialProps in Next.js with TypeScript const X: NextPage = props => {/*...*/} X.getInitialP ...

How can I lower the version of Angular CLI?

Currently, I am working on a project using angular 4 and the angular-cli version 1.6.4 but I am facing this issue while building my project. I have learned that downgrading to angular-cli-1.6.3 can resolve this issue. Could someone advise me on how to do ...