I am learning angular and trying to create reactive form for user authentification. To indicate if my firm work I added {{ LoginForm.value | json }
. But it seems not to work. When I type something into input, correspondent json field doesn't change. I tried to change the way form is build in component, force change but nothing works.
Below is code of component.
Template
<form action="" [formGroup]="LoginForm">
<mat-form-field class="example-full-width" formControlName="loginFormControl">
<mat-label>Login</mat-label>
<input matInput placeholder="" value="">
</mat-form-field>
<p> Value: {{ LoginForm.value | json }}</p>
<label for="">Пароль</label>
<mat-form-field class="example-full-width" formControlName="passwordFormControl">
<mat-label>Password</mat-label>
<input matInput placeholder="">
</mat-form-field>
<!-- <p> Value {{ loginForm.value.loginFormControl}}</p> -->
<p> Value {{ LoginForm.value }}</p>
<button type="submit">Увійти</button>
Component
import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';
import {MatInputModule} from '@angular/material/input';
import {MatFormFieldModule} from '@angular/material/form-field';
import {FormsModule, ReactiveFormsModule,FormControl, FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-loginpage',
imports: [RouterOutlet,
FormsModule,
ReactiveFormsModule,
CommonModule,
MatFormFieldModule,
MatInputModule],
templateUrl: './loginpage.component.html',
styleUrl: './loginpage.component.css',
standalone: true
})
export class LoginpageComponent {
constructor(private fb: FormBuilder) {};
LoginForm!: FormGroup;
// LoginForm = new FormGroup ({
// loginFormControl: new FormControl(''),
// passwordFormControl: new FormControl('')
// });
ngOnInit(): void {
this.LoginForm = this.fb.group (
{
loginFormControl: new FormControl(''),
passwordFormControl: new FormControl('')
}
)
}
}
You should set the formControlName
directive on the input
, not on the mat-form-field
. That is causing the issue.
<mat-form-field class="example-full-width">
<mat-label>Login</mat-label>
<input matInput placeholder="" formControlName="loginFormControl">
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Password</mat-label>
<input matInput placeholder="" formControlName="passwordFormControl">
</mat-form-field>