2 text fields mapped to same formcontrolname angular 2+ - angular6

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
});
}
}

Related

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"

How can I set input placeholder text in component file in Angular

I'm new to Angular and Typescript. I have the input with a placeholder below, is there a way to change the placeholder text from my component file?
<input id="city" class="form-control" placeholder="City or Town">
You can just bind the placeholder attribute. Stackblitz
<input id="city" class="form-control" [placeholder]="placeholder">
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
placeholder = 'Angular';
}

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;

Can't set property value

I'm trying to set initial value of input field using:
<input type="text" id="inputText2" name="inputText2" ngModel #inputText2="ngModel" size="5" autocomplete="off" [value]="'hre'"
autofocus>
Tried everything [value]="example", [ngValue] - here I've got that isn't know property of input field. Thanks for help!
Just let the ngModel handle setting the value for you.
component.html
<input [(ngModel)]="value" />
component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
value = 'hello';
}
Live demo
I'd suggest:
HTML:
<input [(ngModel)]="yourModel" ... />
TS:
...
public class YourComponent{
yourModel: string = '';
...
}
But you can read on other solutions from the official guide here.

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

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