I'm currently trying to complete angulars basics guides, and i'm currently having some issues with reactive forms.
Line 4 in my HTML is throwing this error:
ERROR TypeError: Cannot read property 'value' of undefined
component.html:
<form [formGroup]="loginForm">
<label>
Username:
<input type="text" formControlName="name">
</label>
<p>{{name.value}}</p>
<label>
adress:
<input type="text" formControlName="adress">
</label>
</form>
component.ts:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(
private formbuilder : FormBuilder
) { }
loginForm :FormGroup;
username : FormControl;
adress : FormControl;
ngOnInit() {
this.username = new FormControl('test',Validators.required);
this.adress = new FormControl('something',Validators.required);
this.loginForm = this.formbuilder.group({
name : this.username,
adress : this.adress
})
}
}
I've tried various variations of using the formbuilder, but i havnt yet been able to make it work.
Data is showing up in the input controls i've got in the HTML file, so i thought that maybe html was finished loading before the script, or the other way around, which would result in some undefined errors. But that doesnt appear to be the case, as the error is thrown when i try to edit the text in the input areas as well.
Honestly i've got no idea about why it happens, and i've been through a lot of googling, where i found people with similar issues, i've tried their solutions, but it doesnt seem to work for me.
So please help, thanks in advance.
edit: so appareantly the issue wasnt on line 4 as the console said, but rather on line 6, where i was trying to access the value of a control.
nameis undefined. You can use{{name?.value}}instead, which will only try to readvalueifnameis not null / undefined