Angular2's ngControl is unable to retrieve default values

I have been working on a form using Angular 2 (RC.3) and noticed that the `ngForm` directive is not recognizing default values set with the `value` attribute.

// app.component.html
<form (ngSubmit)="onSubmit(editForm.value)" #editForm="ngForm">
  <input ngControl="firstName" type="text" value="{{user?.firstName}}">
  <input ngControl="lastName" type="text" value="{{user?.lastName}}">

  <input type="submit" value="Edit">
</form>

// app.component.ts
...
export class AppComponent {
  public user: UserModel;

  constructor(private _api: ApiService) {
    // Getting user data.
    this._api.get('/users/self').subscribe(
      (user: UserModel): void => { this.user = user; }
    );
  }
  onSubmit(user: UserModel): void {
    console.log(user);
  }
}

When the `user` object holds data, the `input` elements are populated with the `firstName` and `lastName` from the `user` object. However, if the `value` attribute values are not changed, the `editForm.value` returns empty like below:

{ firstName: null, lastName: null }

If the `input` element values are modified, `editForm.value` reflects these changes. What could be the solution?


I'm also confused about the proper usage of `ngControl` and `ngModel`. While `ngControl` handles validations and operation statuses, `ngModel` is meant to sync presentation layer models. I am unsure about the distinction between `ngControl` and `ngModel`.

It seems like we can retrieve form values using only `ngControl`, rendering `ngModel` and two-way binding unnecessary...

Answer №1

Consider using the following code snippet for your component:

// player.component.ts
import { Component } from "@angular/core";
import { FormBuilder, FormGroup, Validators} from "@angular/forms";
import { APIService } from "./services/api-service";
import { PlayerModel } from "./models/player-model";

@Component({
    templateUrl: "player.component.html",
    providers: [APIService],
})
export class PlayerComponent {

    player: PlayerModel;
    playerForm: FormGroup;

    constructor(private _api: APIService, fb: FormBuilder) {

        // initialize to a new, empty player
        this.player = new PlayerModel();

        // fetch the player data
        this._api.get("players/self").subscribe((player: PlayerModel): void => {
            this.player = player;
        });

        // create a form control group for the form
        this.playerForm = fb.group({
            firstName: [this.player.firstName, Validators.required],
            lastName:  [this.player.lastName,  Validators.required]
        });
    }

    onSubmit($event, player) {
        $event.preventDefault();
        console.log(player);
    }
}

Make sure to include the following in your template:

// player.component.html
<form [formGroup]="playerForm" (submit)="onSubmit($event, player)">
    <input formControlName="firstName" [(ngModel)]="player.firstName" />
    <input formControlName="lastName"  [(ngModel)]="player.lastName"  />
    <input type="submit" value="Update" [disabled]="!playerForm.valid" />
</form>

One issue to watch out for is ensuring that the API response comes back in time to populate the form. Additionally, the submit button will be disabled if the form is invalid, such as when any of the fields are left empty.

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 Search Version 2.0

I am facing an issue with my search functionality in Angular 2. When I type into the search box, the search method on the service is not triggered. I believe there might be a simple solution that I am missing. Any assistance would be greatly appreciated. ...

Incorporating a polling feature into an HTTP request within Angular 8

How can I implement a polling mechanism in order to fetch the status of a job (type Status) every minute for a service that requests this object with a specific JOB_ID as an argument? retrieveJobStatus$(JOB_ID): Observable<Status> { const url = ...

The successful loading of tab favicons in the DOM of an angular chrome extension is a triumph, however, explicit XHR requests are unfortunately

I've been immersed in developing a Chrome extension with Angular 5. Successfully, I managed to extract favIconUrls from the tabs API and link them to my popup.html's DOM. The icons are retrieved and displayed without any hiccups. See an example ...

Error message stating: "The 'MktoForms2' property is not recognized within the scope of 'Window & typeof globalThis'."

Encountering the following error message: (Property 'MktoForms2' does not exist on type 'Window & typeof globalThis') while working with react and typescript useEffect(() => { window.MktoForms2.loadForm("//app-sj11.marke ...

Deploying an Angular application in a NodeJS environment using Azure DevOps

Can Azure DevOps Pipelines be used to automate the deployment of an Angular application to NodeJS or an on-premise WebServer? ...

Problem with Invoking method of parent component from child component in Angular 4

Despite having all my event emitters set up correctly, there's one that seems to be causing issues. child.ts: @Component({ ... outputs: ['fileUploaded'] }) export class childComponent implements OnInit { ... fileUploaded ...

There are critical vulnerabilities in preact-cli, and trying to run npm audit fix leads to a never-ending loop between versions 3.0.5 and 2.2.1

Currently in the process of setting up a preact project using preact-cli: npx --version # 7.4.0 npx preact-cli create typescript frontend Upon completion, the following information is provided: ... added 1947 packages, and audited 1948 packages in 31s 12 ...

What is the resolution if I need to utilize a property that is untyped?

Transitioning to TypeScript from plain old JavaScript is a step I'm taking because I believe it offers significant advantages. However, one drawback that has come to light is that not all attributes are typed, as I recently discovered. For instance: ...

Using an Object as a Key in Maps in Typescript

I had the intention of creating a Map object in Typescript where an object serves as the key and a number is the value. I attempted to define the map object in the following manner: myMap: Map<MyObj,number>; myObj: MyObj; However, when I tried to a ...

Guide to Angular Interface Styling - Ambiguous Suggestions

After reviewing the Angular style guide for interfaces, I find two recommendations particularly perplexing: The suggestion to use a class instead of an interface for services and declarables (components, directives, and pipes) leaves me puzzled. Similarl ...

Error: Trying to access a property that is not declared on an empty object

Using a fully patched Visual Studio 2013, I am integrating JQuery, JQueryUI, JSRender, and TypeScript into my project. However, I am encountering an error in the ts file: Property 'fadeDiv' does not exist on type '{}'. While I believ ...

What is the correct way to invoke a function that accepts a combination of specific string values when all I have is a regular string?

Within the TypeScript function declaration provided below, the parameter type alignment consists of unioned literals. function printText(s: string, alignment: "left" | "right" | "center") { // ... } As per the documentation ...

Can you please explain to me the purpose of the ncu -u command?

Struggling to update my Angular project in Visual Studio to a specific version of Angular. Instead of following the tutorial that provided me with the latest Angular version, I wanted to install version 6 specifically. So, I ran npm install -g @angular/ [ ...

Ways to identify the moment a form becomes 'ready' after the component has been initialized

It seems like I might be making a mistake, as there are instances where I need to make adjustments to a Form or FormControl after a component has initialized and data has been loaded. The problem arises because the form and its controls don't seem to ...

A pattern matching algorithm that verifies a series of port numbers (ranging from 1 to 65535) spread out across

I am in search of a regular expression that can accurately identify valid port numbers (ranging from 1 to 65535) within a text area. The input format will resemble the following: 80 80 25 53 110 --- --- This pattern will continue across multiple lines, wi ...

Issue with Datepicker validation in Angular 5 and Angular Material

I have implemented the most recent version of Angular and Angular Material. I am facing an issue with a datepicker where the validation requirements are not being met as expected. The documentation states that the required attribute should work by default, ...

Finding the number of elements in a FirebaseListObservable involves accessing the `length` property

One of the tasks in my Angular 2 application involves retrieving data from a Firebase database and storing it in a FirebaseListObservable. I have a method called getStatus that is supposed to determine the number of elements in this FirebaseListObservable. ...

The $scope.eval feature in Angular 4 allows for dynamic evaluation

During the era of Angular, we utilized this framework to develop a specialized application for one of our clients. In simple terms, the application was designed to create dynamic questions and answers, even intricate ones, with specific display and validat ...

Issue: (SystemJS) the exports variable is not defined

In the process of developing a .net core mvc + angular application, I encountered an interesting situation. The MVC framework handles user management, and Angular takes over when users navigate to specific areas of the application. Initially, I integrated ...

Angular strictPropertyInitialization - best practices for initializing class members?

When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data. I have considered 3 options. But which one is the most appropriate? Is there another alt ...