Can't wrap my head around capturing form data (Angular) - html

I am simply trying to create a mockup of a login page, and need to get the username and password values entered into the form, and use those values to validate whether the user should be authenticated. I've looked at a dozen tutorials and can't seem to understand it fully. Here is what I have:
login.component.html
<form #f="ngForm" (ngSubmit)="loginUser()">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username"
[(ngModel)]="model.username" #username="ngModel"
class="form-control" required>
<label for="password">Password</label>
<input type="password" id="password" name="password"
[(ngModel)]="model.password" #password="ngModel"
class="form-control" required>
<div style="padding-top:20px">
<button type=submit class="button">Login</button>
</div>
</div>
</form>
login.component.ts (I'm going wrong here somewhere, but I tried. The "if" statement is definitely wrong)
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { NgForm, FormControl, FormGroup, ReactiveFormsModule } from '#angular/forms'
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
myForm: FormGroup
constructor(private router: Router) {
}
ngOnInit() {
}
loginUser(f: NgForm) {
if (f.value == "admin" && f.value == "admin"){
this.router.navigate(['mockup']);
}
}
}

There are a few issues:
1- Model is not defined anywhere. Therefore, model.username is not valid. Just make it username or define model somewhere in your calss.
2-You don't need the variables (#username="ngModel") if you are not going to use them in the template. For example, you could do:
<input #myUsernameInput="ngModel">
{{ myUsernameInput.valid }} // true/false
{{ myUsernameInput.value }} the value
and various other checks. But you aren't performing these checks anywhere, so there's no need to have the variables defined.
3- myForm should not be defined in your class, as formGroups are used for reactive forms, not template driven forms. If you want to pass the values to the method, an easy way is like this:
<form (submit)="loginUser(username, password)">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username"
[(ngModel)]="username" class="form-control" required>
<label for="password">Password</label>
<input type="password" id="password" name="password"
[(ngModel)]="password" class="form-control" required>
<div style="padding-top:20px">
<button type=submit class="button">Login</button>
</div>
</div>
</form>
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { NgForm, FormControl, FormGroup, ReactiveFormsModule } from '#angular/forms'
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit() {
}
loginUser(username: string, password: string) {
if (username === "admin" && password === "admin"){
this.router.navigate(['mockup']);
}
}
}
The easiest way to to explain template driven forms means that all the work (meaning the building of the form, the validation, etc.) takes place in the template (the html). This is limited because you can't do everything that you could with reactive driven forms. However, reactive driven forms are a bit more complex. Which to choose depends on the situation and the preference, but in this scenario, template driven forms are perfectly valid to use. I'd recommend reading this guide, it's super helpful. https://angular.io/guide/forms

Related

Pass value from Typescript to HTML. Error; [object HTMLInputElement]

I try to pass array values from a .ts file to a html file in a Angular Project.
The HTML file is:
<body>
<section id="login" class="d-flex justify-content-center flex-column align-items-center">
<form>
<div class="form-group">
<label>Firmware</label>
<input #firmware class="form-control" type="text" value= {{firmware}} readonly>
</div>
<div class="form-group">
<label>Bootloader</label>
<input #bootloader class="form-control" type="text" value= {{bootloader}} readonly>
</div>
</form>
</section>
</body>
and the .ts file is:
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Router, ActivatedRoute, ParamMap } from '#angular/router';
#Component({
selector: 'app-dual',
templateUrl: './dual.component.html',
styleUrls: ['./dual.component.scss']
})
export class DualComponent implements OnInit {
title = "";
constructor(private router: Router, private httpClient : HttpClient) { }
ngOnInit(): void {
var resultArray:number[] = [235,23]
var firmware = resultArray[0];
var bootloader = resultArray[1];
console.log("firmware",firmware);
console.log("bootloader",bootloader);
}
}
If i show the values via console.log they are shown right but if i try to show them in the HTML file the value in the textbox is "[object HTMLInputElement]"
Note: Im new in Angular and try to learn :)
Any tips?
Thank you!
Solution:
HTML:
<div class="form-group">
<label>Firmware</label>
<input class="form-control" type="text" value= {{firmware}} readonly>
</div>
<div class="form-group">
<label>Bootloader</label>
<input class="form-control" type="text" value= {{bootloader}} readonly>
</div>
TypeScript:
var resultArray:number[] = [235,23]
this.firmware = resultArray[0].toString();
this.bootloader = resultArray[1].toString();
console.log("firmware",this.firmware);
console.log("bootloader",this.bootloader);
I deleted my old answer, because I totally missed what was wrong. When you do this:
<input #firmware class="form-control" type="text" value= {{firmware}} readonly>
The #firmware creates a new local variable named firmware, which is equal to the HTML element it's contained in. It's that new local variable that is being displayed inside the curly braces, not the variable firmware which is defined in your DualComponent class.
Make sure you don't duplicate variable names like this, and the problem will go away.

How to make a html form to angular form

I have created an component called login. I have created a html form login.component.html then I wanted to make this form as Angular form. So I added <form #loginform="ngForm"> in login.component.html and import import {NgForm} from '#angular/forms' in login.component.ts. Can you help me where is the issue?
So when I run the server I get an error said:
ERROR in src/app/login/login.component.html:2:23 - error NG8003: No directive found with exportAs 'ngForm'.
2 <form #loginform="ngForm">
~~~~~~
src/app/login/login.component.ts:6:16
6 templateUrl: './login.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component LoginComponent.
login.component.ts:
import { Component, OnInit } from '#angular/core';
import {NgForm} from '#angular/forms';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
login.component.html:
<div class="container">
<form #loginform="ngForm">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Login</button>
</form>
</div>
Maybe if you add the FormsModule to the your Module, your problem will be solved or you can create login component by Command ng g c login
Do not use ngForm. Use angular reactive forms it is better and easier to create and manage.
https://angular.io/guide/reactive-forms
but if you want to continue with the current setup please check this answer
TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

ngModel in Angular Form

I'm trying to access to data form my form in the TS file.
I got error : RROR TypeError: Cannot read property 'name' of undefined
My code is like this:
import { Component, OnInit } from '#angular/core';
import { employee } from '../models/Employee';
import { NgForm } from '#angular/forms';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
#Component({
selector: 'app-employee-form',
templateUrl: './employee-form.component.html',
styleUrls: ['./employee-form.component.css']
})
export class EmployeeFormComponent implements OnInit {\
data: employee;
constructor() { }
ngOnInit() {
}
onSubmit(form:NgForm ) {
alert("Hello " + JSON.stringify(this.data));
}
}
<div class="container">
<form #form="ngForm" (ngSubmit)="onSubmit(form)">
<div class="form-group">
<label for="form">name</label>
<input type="text" class="form-control" id="name" [(ngModel)]="data.name" required>
</div>
</div>
<button type="submit" class="btn btn-success" >Submit</button>
</form>
</div>
I didnt find my mistake, any idea?
thanks
Do the template binding with a safe navigation operator. This way, if "data" is not defined, your code will not try to read prop name from it.
<input type="text" class="form-control" id="name" [(ngModel)]="data?.name" required>
In case, if the prop data is undefined and you want to use data as a container to store the form values then you have to at least create an empty object, for example, initialize data as data = {} It will create keys on the fly.
The solution is that you shouldn't make the data null ever.
And initialize the data as
data = {} as employee;

2 text fields mapped to same formcontrolname angular 2+

I have a requirement where in i have 2 search fields one on top and one on bottom. Need to keep both text fields in sync i.e. user can type in top or bottom search text box. If he types in top box it should reflect in bottom box and vice versa. I am using reactive angular forms
HTML Code:-
<form [formGroup]="form">
<div class="form-group">
<label for="searchBox1">Search Box 1</label>
<input type="text" class="form-control" id="searchBox1" name="searchBox1"
formControlName="searchBox" placeholder="Search Box 1" (change)="addText($event.target.value)">
</div>
<div class="form-group">
<label for="searchBox2">Search Box 2</label>
<input type="text" class="form-control" id="searchBox2" name="searchBox2"
formControlName="searchBox" placeholder="Search Box 2" (change)="addText($event.target.value)">
</div>
</form>
component.ts code:-
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
'searchBox': new FormControl(null, Validators.required)
});
}
addText(value) {
this.form.setValue({
'searchBox': value
});
}
}

Getting the same values 2 times in console,angular2

When i am seeing the data that comes from form in console it get two times
My template
<div class="login jumbotron center-block">
<h1>Login</h1>
<form #form ="ngForm" (ngSubmit)="onSubmit(form.value)">
<div class="form-group">
<label for="username">Username</label>
<input type="text" ngControl ="email" class="form-control" id="emailh" placeholder="Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" ngControl ="phone" class="form-control" id="phoneh" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<a [routerLink]="['/signup']">Click here to Signup</a>
</form>
</div>
My component,
import { Component } from '#angular/core';
import { Router, ROUTER_DIRECTIVES } from '#angular/router';
import { CORE_DIRECTIVES, FORM_DIRECTIVES } from '#angular/common';
import { Http, Headers } from '#angular/http';
import { contentHeaders } from '../headers/headers';
import {Control,FormBuilder,ControlGroup,Validators} from '#angular/common';
#Component({
directives: [ ROUTER_DIRECTIVES, CORE_DIRECTIVES, FORM_DIRECTIVES ],
templateUrl : "./components/login/login.html",
})
export class Login {
constructor(public router: Router, public http: Http) {
}
onSubmit(form:any) {
console.log(form);
}
}
my console,
Object {email: "andrew#gmail.com", phone: "getiyt"}
Object {email: "andrew#gmail.com", phone: "getiyt"}
When i am seeing the data that comes from form in console it get two times,therefor i am not sure that why it comes like that as a result my db also get filled with single record 2 times.Can someone find where i am wrong.
In your main.ts you have to set:
import {disableDeprecatedForms, provideForms} from '#angular/forms';
bootstrap(AppComponent, [disableDeprecatedForms(), provideForms()]);
This solve the problem. See this plunker: http://plnkr.co/edit/uiYZkEWMyXWOkglHZu6N
See also the official documentation: https://angular.io/docs/ts/latest/guide/forms.html
Credit: Roberto Simonetti's answer here.