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.