Default values using Observables in Angular 2 Formbuilder

I am encountering an issue with setting the default value of an Angular 2 Form (formbuilder). In my case, the default values are observables retrieved from a server, so I am unable to implement them in the usual way:

export class UserComponent implements OnInit{

userForm: ControlGroup;
userData: any; // Initialize the observable variable

ngOnInit():any {

    this.userData = this._dataService.getAllData() // My Observable
        .subscribe(
            data => {
                this.userData = data;
            }
        );

    this.userForm = this._formBuilder.group({
                  // Setting the default value below
        'username': [this.userData.username, Validators.compose([ 
            this.usernameValid
        ])]
}

Does anyone have any suggestions on what changes need to be made? The form is currently not displaying anything inside the input fields...

Answer №1

One approach to consider is dealing with the asynchronously loaded data. It's essential to ensure that form elements are updated once the response has been received.

ngOnInit():any {
  this.userData = this._dataService.getAllData()
    .subscribe(
      data => {
        this.userData = data;
        this.userForm.controls.username.updateValue(
                this.userData.username);
      }
    );

  this.userForm = this._formBuilder.group({
    'username': [this.userData.username, Validators.compose([ 
        this.usernameValid
    ])];
}

Answer №2

Another way to achieve this functionality is through the following method:

data: Observable<any>;

ngOnInit():any {

   this.data = this._dataService.getAllData();

   this.data
      .map((details) => {
         return this._formBuilder.group({
            username: [ this.data.username,
               Validators.compose([this.usernameValid])
            ]
      })
      .subscribe((userDetails) => {
         this.userDetails = userDetails
      })

}

To display this in your template, you can utilize the async pipe as demonstrated below:

<form *ngIf="data | async" [formGroup]="userDetails">
   //...//
</form>

This approach eliminates the need for calling updateValue(), making it simpler to manage multiple fields that require default values from observables.

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

Angular Material Dropdown with Multi-Column Support

I'm working on customizing the selection panel layout to display items in multiple columns. However, I'm facing an issue where the last item in each column appears off-center and split, causing overflow into the next column instead of a vertical ...

What is the best way to compress a file for transfer to a server using gzip?

While attempting to upload a file and send it to the server via a REST API, I am looking for a reliable method to gzip the file. Unfortunately, there is limited documentation available on this topic. Can anyone suggest the most effective approach to achiev ...

TypeScript unable to loop through object with string keys

My TypeScript service is responsible for populating an associative array: fun populateData(){ let tempArr; tempArr = []; this.service.get('Post', 1, 'true').subscribe( (response) => { this.loadingIcon = false; ...

What is the best way to test an oclif CLI tool that interacts with a Rest API

How can I efficiently test the TypeScript code I've written for an Oclif CLI that interacts with a Node.js and Express.js REST API? I'm currently using Mocha/Chai for testing, but I'm struggling with testing the specific command code from my ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

The ng-content directive fails to display the component containing the host attribute

I can't figure out why ng-content isn't displaying the component with a host attribute. When inspecting the generated HTML DOM, the attribute is present in the host tag but ng-content doesn't have any children. @UPDATE: Following @Naren M ...

Is there a way to create a stub for the given function using sinon?

Here is my test function: const customTestLibrary = require("./test"); describe("Initial Test", function() { it("should run the test function successfully", function(done) { customTestLibrary.execute(); done(); }); }); The te ...

Troubleshooting a date problem in Angular

https://i.sstatic.net/zQLV9.png In my code, I encountered a peculiar issue with a date object. After setting the date to 01 April 2000, I noticed in the debugger that it was correctly set to this date. However, when I attempted to retrieve the month using ...

Does HttpClient's post method exclusively accept Observers?

Currently, I am using the latest version of Angular which is 7. My question is, does the HttpClient post() method only accept Observers? I encountered an issue where I attempted to use a chain of Promises. One node in the chain involves calculations, whi ...

'This' loses its value within a function once the decorator is applied

Scenario: Exploring the creation of a decorator to implement an interceptor for formatting output. Issue at Hand: Encountering 'this' becoming undefined post application of the decorator. // custom decorator function UseAfter(this: any, fn: (.. ...

Submitting a Symfony 2 form with embedded file upload functionality using asynchronous JavaScript and XML (AJ

I've been working on creating an embedded file uploading form with file validation in Symfony 2. I found a helpful example for file uploading here and for embedded forms, I referred to this guide. Everything is working perfectly, but now I need to sub ...

Build modern web applications with Visual Studio 2015/2017 using React and TypeScript for dynamic

Has anyone successfully found a comprehensive react+typescript tutorial for a Visual Studio 2015/2017 MVC project that actually works, from beginning to end? I attempted to install the NuGet packages "Reactjs Mvc4" and "typescript", created a .tsx file, a ...

TypeScript: Defining a parent class type for its children

Dilemma I am seeking a way to structure a JSON object containing three different types of objects, all derived from the same parent object. Additionally, I wish to designate their specific types for improved Intellisense functionality within my codebase w ...

Unable to bring in a personalized npm package using its package title

Currently, I am loosely following a tutorial on creating an angular npm package named customlib. This package is intended for managing dependencies across my projects without the need to make them public on npm. The tutorial can be found here. However, I ...

Modifying the text of a material UI button depending on a particular condition

I have a component that uses the Material UI button, and I need to change the text of the button based on a condition. If the order amount is 0, I want it to display "cancel", otherwise, it should show "refund". Can someone guide me on how to achieve thi ...

Tips for releasing the "Angular and ASP.Net Core" template directly from Visual Studio 2022

I am currently in the process of deploying a sample .net8/Angular application that I have developed using the "Angular and ASP.Net Core" template available in Visual Studio 2022, from GitLab to a CloudFoundry server. However, it seems that there may be an ...

Utilizing discriminated unions in conjunction with classes: A step-by-step guide

I'm having an issue converting a discriminated union into a string. The union comprises two interfaces. When I use the function with a simple object that matches one of the interfaces, I get the desired output. However, if I use a class that implement ...

Stop form from submitting on bootstrap input, still check for valid input

Encountering a dilemma here: Employing bootstrap form for user input and utilizing jQuery's preventDefault() to halt the form submission process (relying on AJAX instead). Yet, this approach hinders the input validation functionality provided by boots ...

Extract the event.data value from a window.addEventListener (MessageEvent) in order to trigger a separate function

Currently, I am delving into Angular and aiming to develop a LinkedIn Login API. To achieve this, I'm utilizing window.open to launch a new window where the user can either accept or decline the authorization. Upon successful acceptance, LinkedIn retu ...

How can I fix the issue of 'trailing whitespace' in my angular2 application?

While running my Angular2 application using 'npm start' in the command prompt, I am encountering numerous warnings about 'trailing whitespace'. Is there a single solution to resolve all of them at once? The total number of these warning ...