How to pre-fill 3 formgroups when initializing in Angular 2?

I currently have this code that allows users to add a new set of fields. However, I am looking to have the component render out 3 sets of data upon initialization.

Currently, one set of fields is generated using the initRateRow function. How can I modify it to iterate through an HttpClientModule and populate the "this._fb.group" accordingly?

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-exchange-rates',
  templateUrl: './exchange-rates.component.html',
  styleUrls: ['./exchange-rates.component.scss']
})
export class ExchangeRatesComponent implements OnInit {

    public myForm: FormGroup;

    constructor(private _fb: FormBuilder) { }

    ngOnInit() {
        this.myForm = this._fb.group({
            rates: this._fb.array([
                this.initRateRow(),
            ])
        });
    }

    initRateRow() {
        return this._fb.group({
            rateUnit: ['24', Validators.required],
            currencyFrom: ['GBP', Validators.required],
            currencyTo: ['USD', Validators.required]
        });
    }

    blankRateRow() {
        return this._fb.group({
            rateUnit: ['', Validators.required],
            currencyFrom: ['', Validators.required],
            currencyTo: ['', Validators.required]
        });
    }

    addRateRow() {
        const control = <FormArray>this.myForm.controls['rates'];
        control.push(this.blankRateRow());
    }

    removeRateRow(i: number) {
        const control = <FormArray>this.myForm.controls['rates'];
        control.removeAt(i);
    }

    save(model) {
        // call API to save
        // ...
        console.log(model);
    }

}

Answer №1

If you want to fetch data in Angular, you can accomplish this within the ngOnInit() lifecycle hook.

ngOnInit(){
    let url = '/getData'; // This is where you would specify your API endpoint
    this.http.get(url)
        .map(response => response.json())
        .subscribe(data => data.forEach(item => {

            // Perform actions with each item received from the API

        }));
}

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

Show the menu when hovering in reactjs

Currently, in my react project, I am implementing dropdown menus using the reactstrap css framework. Example.Js <Dropdown className="d-inline-block" onMouseOver={this.onMouseEnter} onMouseLeave={this.onMouseLeave} ...

Filtering DataGrid columns with an external button in Material-UI: A step-by-step guide

Imagine having a datagrid table structured as shown below: import * as React from 'react'; import { DataGrid, GridToolbar } from '@mui/x-data-grid'; import { useDemoData } from '@mui/x-data-grid-generator'; const VISIBLE_FIEL ...

Connect an HTML button to a Java activity

I am currently developing an Android app for my book and I have created an HTML page. I would like to add a button on this page that is linked to the following Java code: public class MainActivity extends Activity { @Override public void onCreate(Bundle ...

Error message: The object is not visible due to the removal of .shading in THREE.MeshPhongMaterial by three-mtl-loader

Yesterday I posted a question on StackOverflow about an issue with my code (Uncaught TypeError: THREE.MTLLoader is not a constructor 2.0). Initially, I thought I had solved the problem but now new questions have surfaced: Even though I have installed &apo ...

Is the length of a complex match in Angular JS ng-if and ng-repeat greater than a specified value?

In my code, there is an ng-repeat that generates a table based on one loop, and within each row, another cell is populated based on a different loop: <tbody> <tr ng-repeat="r in roles | limitTo: 30"> <td>{{r.name}}</td> ...

Manipulating data with Angular 2 services: accessing and updating values

This code snippet is all about managing an array in Angular. The Injectable decorator is used to define a service called Svc with methods for setting and getting column definitions. import { Injectable } from '@angular/core'; @Injectable() ...

Changing the Size of X-Axis Labels Font in a Line Chart Using ChartJS

Struggling with adjusting the font size of x-axis labels in my line chart design using ChartJS. I've attempted to set the x-axis ticks to my desired size, but the font size remains unchanged: options:{ scales:{ xAxis: [{ ...

Discover how to access and manipulate JSON files in an Angular application using

Currently, I am diving into learning TypeScript with Angular and I'm interested in reading a JSON file. The structure of my JSON file is as follows: { "nb": "7", "extport": "1176",, "REQ_EMAIL": ...

The use of HTML5 required attribute is ineffective when submitting forms via AJAX

Seeking advice on implementing basic validation for a newsletter form that only requires an email address. The current page layout doesn't allow space for jQuery error messages, so I attempted to use the HTML 5 required attribute. However, the form st ...

Can someone show me how to properly set up nested child routes in Angular 2?

My application structure is organized as shown below . ├── photos ├── posts ├── users │   ├── detail │   │   ├── address │   │   ├── family │   │   ├── information │   │   └ ...

How can I conceal login and register router-links in the Vue + Laravel SPA project navbar immediately after a user logs in?

Currently, I am working on my Bachelor's degree project and have encountered a specific issue. While the login, register, and logout functions all seem to be working well, there is an inconsistency with the navigation bar not automatically switching b ...

Adding numerous objects to a Vuex store using mutations

I am currently working with the following store setup: import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ plugins: [createPersistedState()], state: { ...

The compatibility issue arises when using Material UI Portal with TypeScript, specifically with the 'children' property types

When rendering a component using Material-UI Portal that includes several Material UI buttons, the following code is used: <Portal container={this.myContainer}> <Button onClick={this.handleClick}>Do something</Button> //other but ...

Troubleshooting issue: Inability to assign classes to child elements within divs of a designated class

Currently, I am facing an issue while attempting to insert divs into multiple divs that share a common class called ".description". My goal is to assign a unique class to each internal div, but for some reason, this only seems to work for the first div w ...

Creating an array of logos in ReactJS with the help of TailwindCSS

After seeing multiple implementations of this feature, I find myself struggling to search for a solution. I can only access the HTML and CSS through inspecting elements, wondering if others are facing the same issue as me. Typically, we aim to implement t ...

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...

Develop a video in mp4 format using Node.js and ffmpeg by combining two or more jpg images

I am currently working on a video animator project where I generate .jpg images from an html canvas tag and then use these images as frames for the video. The tool I am using for video generation is ffmpeg. Successful with Single Image const ffmpeg = req ...

JavaScript error: Function is not defined when using Paper.js

UPDATE the problem has been solved by making the colorChange function global I am attempting to modify the color of the path when the 'Red' button is clicked using the colorChange function. Despite my efforts, I keep getting an error stating tha ...

Encountering an unknown value within the inner array of a JSON response when using Angular

I received the following JSON data from an API: [ { "CinemaId": "Hfsdfsdfs", "FilmCode": "HIWdfsdfsfsf47", "FilmTitle": "BAfsdfAAR", "CinemaName": "CsfsnfsfsAhmedabad", "CinemaCity": "Ahmedabad", "CinemaLicenseName": "BIGdfsfsAh ...

Oops! Looks like there's a type error in module "*.mdx" - it seems that it doesn't have the exported member "metadata". Maybe try using "import metadata from "*.mdx"" instead?

I am attempting to extract metadata from an mdx file. I have followed the guidelines outlined in NextJS Markdown Frontmatter, but encountered build errors. It is important to note that I am unable to utilize fs. Code Section Page.tsx File import Conte ...