How come I'm able to access the form's control within setTimeout but not outside of it?

Having just started working with Angular, I came across a strange issue involving forms and setTimeout. When trying to access the form control of an input element inside setTimeout within the OnInit lifecycle hook, it works fine. However, when attempting to access it outside of setTimeout, it does not work. The timeout for setTimeout is set to 0 milliseconds. Any idea what could be causing this behavior? I would prefer not to wrap it inside a setTimeout function...

Template:

<form #f="ngForm">
    <div class="form-group">
      <label for="email">Email address:</label>
      <input type="text"
             name="email"
             id="email"
             [(ngModel)]="model.email"
             required
             email>
    </div>
    <div class="form-group">
      <label for="subscription">Select subscription:</label>
      <select name="subscription"
              id="subscription"
              [(ngModel)]="model.subscription">
        <option value="basic">Basic</option>
        <option value="advanced">Advanced</option>
        <option value="pro">Pro</option>
      </select>
    </div>
    <div class="form-group">
      <label for="password">Password:</label>
      <input type="text"
             name="password"
             id="password"
             [(ngModel)]="model.password"
             required>
    </div>
    <button type="submit">Submit</button>
  </form>
  

Component:

import { Component, ViewChild, OnInit } from '@angular/core';
  import { NgForm } from '@angular/forms';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent implements OnInit {
    @ViewChild('f') f: NgForm;

    model = {
      email: '',
      subscription: 'advanced',
      password: ''
    };

    constructor() {}

    ngOnInit(): void {
      setTimeout(() => {
        console.log(this.f.form.get('subscription')); // Works
      }, 0);
      console.log(this.f.form.get('subscription')); // Doesn't work
    }
  }
  

Thank you in advance for your help, and please excuse any errors in my English.

Answer №1

The issue arises when attempting to access the form outside of the setTimeout function because the form has not yet been created when ngOnInit is called. However, code executed within a setTimeout function runs in a different tick, allowing enough time for the form to be generated.

According to the official documentation:

ngOnInit is triggered right after the directive's data-bound properties are checked for the first time, but before its children are inspected. It is only called once during the instantiation of the directive.

The form becomes accessible once the ngAfterViewInit lifecycle hook is activated. Refer to this link to explore all available lifecycle hooks and learn how to leverage them effectively.

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

What is the process for turning off minifying bundles when constructing an Angular application?

After developing an Angular project and implementing Server Side Rendering (SSR) using the angular-universal package, I have successfully served my project with SSR on port localhost:4000. Now, I am looking to debug it in a similar way as we do in the sour ...

Discover the process of dynamically importing JavaScript libraries, modules, and non-component elements within a Next.js

Lately, I have been utilizing Next.js and mastering its dynamic import feature for importing components with named exports. However, I recently encountered a particular npm package that functions only on the client-side (requires window) and has a substant ...

The promise callback in Angular2 is unable to access this

This snippet of code is quite odd, but it resides within a service context: constructor() { gapi.load('client:auth2', this.loadGoogleApi); } private loadGoogleApi() { // Array of API discovery doc URLs for APIs used by the quickstart ...

Tips on implementing computed properties in Vue.js while using TypeScript

There is a significant amount of documentation on how to utilize Vue.js with JavaScript, but very little information on using TypeScript. The question arises: how do you create computed properties in a vue component when working with TypeScript? According ...

Connecting Ag Grid with modules

Unable to link with modules as it's not a recognized attribute of ag-grid-angular https://i.sstatic.net/2zwY2.png <ag-grid-angular #agGrid style="width: 100%; height: 100%;" id="myGrid" class="ag-theme-balham" [mod ...

Struggling to map the response data received from an http Get request to a TypeScript object that follows a similar structure

Currently, I am invoking an http Get service method from a component to retrieve data and map it to a Person object. The goal is to display this information on the front end. Below is my component code: export class DisplayPersonComponent implements OnIni ...

Tips for sorting multiple rows based on the primary column in MUI DataGrid ReactJS

https://i.stack.imgur.com/T9ODr.png Is there a way to utilize Material UI DataGrid to build a table that matches the structure displayed in the linked image? I have successfully created a basic table with DataGrid, but I'm struggling to add multiple ...

What is the ternary operation syntax for setting the img src attribute in Angular 8?

My data includes a property called "photo" which can either have a file name or be empty. For instance, it could be "steve.jpg" or just an empty string if Steve does not have a photo. In React JSX, I know how to use a ternary operator with the "photo" va ...

Angular 2: A Beginner's Guide to Creating Objects and Transforming Code from Angular to Angular 2

Currently, I am learning Angular 2 and facing an issue. I am unsure about how to create an object in my login function (Angular1). public logIn() { let phone = this.user.number.replace(/\s+/g, ''); let email = 'u&a ...

Optimizing Angular6 Pipe Filter Performance for Large Arrays

I have written a filter that retrieves a subset of items from a large array consisting of around 500 items. import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchFilter' }) @Inject ...

Tips for utilizing favicons-webpack-plugin in Angular 8 applications?

I am attempting to incorporate the jantimon/favicons-webpack-plugin into an Angular 8 project. To achieve this, I'm utilizing the @angular-builders/custom-webpack package to develop a custom webpack configuration. const FaviconsWebpackPlugin = requir ...

Leveraging AWS CDK to seamlessly integrate an established data pipeline into your infrastructure

I currently have a data pipeline set up manually, but now I want to transition to using CDK code for management. How can I achieve this using the AWS CDK TypeScript library to locate and manage this data pipeline? For example, with AWS SNS, we can utilize ...

How can I configure a mocked dependency in Jest to return a specific value in a function?

I am currently working on simulating a mongoose model to facilitate unit testing for an express controller. To keep things simple, I've removed all unnecessary code and provided below the specific scenario I'm dealing with. Here's the snippe ...

How do I implement branch code using TypeScript types in Svelte?

Looking for a solution similar to the one mentioned in Typescript: How to branch based on type, but tailored for Svelte. Despite implementing run-time type guards as suggested, Svelte continues to throw errors. I am dealing with an array called collectabl ...

Learn how to easily reset the index value within the same template in Angular

In my template, I have 3 tables with the same JSON data as their parent elements. <tbody> <ng-container *ngFor="let row of reportingData.RecommendationData; let i=index"> <tr *ngIf="row.swRecommendations"> <td& ...

How can I set up a KeyboardEvent listener in JavaScript?

My attempt to use @keydown resulted in an error: Type 'Event | KeyboardEvent' is not assignable to type 'KeyboardEvent'. Type 'Event' is missing the following properties from type 'KeyboardEvent': altKey, c ...

Creating a Variety of Files in the Angular Compilation Process

Currently, I am developing an Angular project and faced with the task of creating various files during the build process depending on certain conditions or setups. I would appreciate any advice on how to accomplish this within the Angular framework. I att ...

Troubleshooting problem with Angular HttpClient when invoking Bing Maps Locations REST APIs

Currently, I have successfully implemented a Bing Maps call using Angular 4 Http service: this.http.get("{absolute URL of Bing Maps REST Locations, with options and key}") Now, I am trying to transition this call to use the newer HttpClient service in An ...

The functionality of the Bootstrap collapse menu is not compatible with Angular

I'm experiencing difficulties with implementing the "collapse" effect in the menu using bootstrap and angular. I have set up the layout separately and everything seems to be functioning correctly, but as soon as I integrate angular, the menu stops wor ...

There are missing dependencies for the designated entry point, "@vcd/ui-components."

Upon running the application with npm start from the branch named ryan-a11y-merge-to-master at https://github.com/juanmendes/vmware-cloud-director-ui-components, I encountered the following error. However, when I switch to the master branch, no errors are ...