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

Tips for dynamically implementing a pipe in Angular 5

In my Angular application, I have implemented a filter using a pipe to search for option values based on user input. This filter is applied at the field level within a dynamically generated form constructed using an ngFor loop and populated with data from ...

The Angular application continues to display the outdated component HTML template in the browser even after it has been updated

In my role, I am currently focusing on developing Angular libraries that can be reused across various projects within our software department. One of these libraries includes a login form that I have successfully published to npm and integrated into anothe ...

Icon positioned to the left within the text box

Hey there! I'm new to NativeScript and I've been struggling to place an icon inside a textbox. Can someone please help me out? Expected Output: https://i.stack.imgur.com/xvoZG.png Code <GridLayout columns="*, *" rows=& ...

Service function in Angular 2 is returning an undefined value

There are two services in my project, namely AuthService and AuthRedirectService. The AuthService utilizes the Http service to fetch simple data {"status": 4} from the server and then returns the status number by calling response.json().status. On the ot ...

Discover the Prisma findMany method for implementing tanstack react table functionality

I'm looking to build a table (using tanstack table) populated with data fetched from Prisma.findMany. Let's suppose I have a User model: model User { id Int @id @default(autoincrement()) name String age String email String } Now, in my p ...

Unable to exclude modules from ng-build in Angular CLI, the feature is not functioning as intended

I am managing an Angular CLI project that consists of two identical apps. However, one app requires the exclusion of a specific module in its build process. Key Details: Angular CLI Version: 1.7.4 Angular Version: 5.2.10 In the angular-cli.json ...

Angular 2 wrap-up: How to seamlessly transfer filter data from Filter Component to App Component

A filtering app has been created successfully, but there is a desire to separate the filtering functionality into its own component (filtering.component.ts) and pass the selected values back to the listing component (app.ts) using @Input and @Output functi ...

Implementing a Set polyfill in webpack fails to address the issues

Encountering "Can't find variable: Set" errors in older browsers during production. Assumed it's due to Typescript and Webpack leveraging es6 features aggressively. Shouldn't be a problem since I've successfully polyfilled Object.assign ...

The ElementRef was modified following the activation of a click event

Let me explain my current situation: I am working with 3 components: MainComponent, ComponentA, and ComponentB. MainComponent dynamically loads ComponentA. ComponentA contains a button that, when clicked, calls MainComponent.addComponent(ComponentB). exp ...

Accessing data retrieved from an API Subscribe method in Angular from an external source

Below is the Angular code block I have written: demandCurveInfo = []; ngOnInit() { this.zone.runOutsideAngular(() => { Promise.all([ import('@amcharts/amcharts4/core'), import('@amcharts/amcharts4/charts') ...

How can I rename an event function in Angular 2?

Is it possible to dynamically change the function associated with an event? I attempted to do so like this: (click) = "{{myFunction}}" However, I encountered an error stating "Parser Error: Got interpolation ({{}}) where expression was expected". I am lo ...

Selected Angular Radio Button

Back in the good ole days of basic HTML and CSS, I was able to achieve the following: input:checked+label { background-color: #f00; } <div class="col-xs-6"> <input type="radio" id="template-1" name="template" value="template1" checked> ...

What might be causing my observable to fail to return a value?

I'm currently utilizing an API known as ngx-pwa localstorage, which serves as a wrapper for an indexeddb database. Within my Angular project, I have a service that interacts with this database through a method called getItem: getItem(key: string) { ...

Understanding the limitations of function overloading in Typescript

Many inquiries revolve around the workings of function overloading in Typescript, such as this discussion on Stack Overflow. However, one question that seems to be missing is 'why does it operate in this particular manner?' The current implementa ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

Issues with animations in Ionic 3 and Angular 4 not functioning as expected

Working on a component to animate an accordion list, I made all the necessary changes such as importing import { BrowserModule } from "@angular/platform-browser"; and import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; as well ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

What is the best way for me to access a certain web address?

I am working on setting up a routing mechanism in my Angular project, but I'm encountering a URL routing error. The application is unable to locate the specified URL. Below is the routing setup: navigation.ts { id: 'documentation-manag ...

Cricket score update features on the client side

Looking for assistance with client-side code development! I am currently working on an Android application using Ionic that involves live cricket scores. I have purchased a cricket API and understand how to connect to it using Node.js on the server side. ...