I have a simple form
<form role="form" (submit)="login()">
<input type="text" name="username" id="username" required="required" [ngModel]="credentials.username"/>
<input type="password" name="password" id="password" required="required" [ngModel]="credentials.password" />
<button type="submit">Sign in</button>
</div>
</form>
and a component ts.
export class LoginComponent implements OnInit {
credentials = {username: '', password: ''};
constructor(private loginService: LoginService, private http: HttpClient, private router: Router) { }
ngOnInit() { }
login() {
console.log(this.credentials);
this.loginService.authenticate(this.credentials, () => {
this.router.navigateByUrl('/');
});
return false;
}
}
service
authenticate(credentials, callback) {
console.log(credentials);
const headers = new HttpHeaders(credentials ? {
authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
} : {});
}
My problem is that the credentials are always ''. Shouldn't the ngModel update these values automatically?
You should use [(ngModel)] to set values like this -
<input type="text" name="username" id="username" placeholder="Username" required="required" [(ngModel)]="credentials.username"/>
<input type="password" name="password" id="password" placeholder="Password" required="required" [(ngModel)]="credentials.password" />
As of now, you are using [ngmodel] which is just attribute binding to set value into your DOM and display it back.
But if you want to update value from view part you should use two way data binding [(ngModel)]
You have to use [(ngModel)] instead of [ngModel]
<input type="text" name="username" id="username" placeholder="Username" required="required" [(ngModel)]="credentials.username"/>
<input type="password" name="password" id="password" placeholder="Password" required="required" [(ngModel)]="credentials.password" />
because [( in Angular is signalling a two-way data binding. Theoretically you could only bind to an event (ngModel) or to a value [ngModel]. But in this case you need to use two-way data binding : [(ngModel)]
Related
My Html file is as follows:
<h2>Welcome User!!!</h2>
<form class="container" action="/product">
<div>
<label for="mail"><b>Email-ID: [(ngModel)]</b></label>
<input type="text" placeholder="Enter mail ID" [(ngModel)]="mail" name="mail" required>
<label for="psw"><b>Phone Number</b></label>
<input type="text" placeholder="Enter Phone Number" [(ngModel)]="mail" name="phoneNumber" required>
<button (click)="myFunc()">NEXT</button>
</div>
</form>
My Typescript file is as follows:
import { Component, NgModule, OnInit } from '#angular/core';
import { Router, RouterModule, Routes } from '#angular/router';
import { MyProductPageComponent } from '../my-product-page/my-product-page.component';
#Component({
selector: 'app-my-home-page',
templateUrl: './my-home-page.component.html',
styleUrls: ['./my-home-page.component.css']
})
export class MyHomePageComponent implements OnInit {
phoneNumber = "";
mailID = "";
constructor(private router: Router) {
}
ngOnInit(): void {
}
myFunc() {
localStorage.setItem("phoneNumber", this.phoneNumber);
localStorage.setItem("mail", this.mailID);
this.router.navigate(['/products']);
}
}
const routes: Routes = [
{ path: 'MyProductPageComponent', component: MyProductPageComponent },
]
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
I want to fetch Phone number and Mail ID entered in form and save that in Local Storage. And redirect to the next page. Please help.
Am getting this error: Declaration expected.
you need to use ngmodel to bind the value with input control and same you can access in your component.
<h2>Welcome User!!!</h2>
<form class="container" action="/product">
<div>
<label for="mail"><b>Email-ID: </b></label>
<input type="text" [(ngModel)]="mailID" placeholder="Enter mail ID" name="mail" required>
<label for="psw"><b>Phone Number</b></label>
<input type="text" placeholder="Enter Phone Number" name="phoneNumber" [(ngModel)]="phoneNumber" required>
<button (click)="myFunc()">NEXT</button>
</div>
</form>
Add variables to phone/mail in your .ts components
Use this to variables in myFunc() to get the value of the variables
Use ngModel to bind the variables with the input of the user (set ngModel on the input not label).
Use import { NgModule } from '#angular/core'; in the app.module and NOT in your component
see working code
<h2>Welcome User!!!</h2>
<form class="container" action="/product">
<div>
<label for="mail"><b>Email-ID:</b></label>
<input type="text" placeholder="Enter mail ID" [(ngModel)]="mail" name="mail" required>
<label for="psw"><b>Phone Number</b></label>
<input type="text" placeholder="Enter Phone Number" [(ngModel)]="phoneNumber" name="phoneNumber" required>
<button (click)="myFunc()">NEXT</button>
</div>
</form>
phoneNumber = "";
mailID = "";
myFunc() {
localStorage.setItem("phoneNumber", this.phoneNumber);
localStorage.setItem("mail", this.mailID);
}
const routes: Routes = [
{ path: 'MyProductPageComponent', component: MyProductPageComponent },
]
The path variable should not have a component and you are using router.navigate('/products')
const routes: Routes = [
{ path: 'products', component: MyProductPageComponent },
]
These variables which are used in the ts should bind with the ngModel used in the template
phoneNumber = "";
mailID = "";
<h2>Welcome User!!!</h2>
<form class="container" action="/product">
<div>
<label for="mail"><b>Email-ID: </b></label>
<input type="text" placeholder="Enter mail ID" [(ngModel)]="mailID" name="mail" required>
<label for="psw"><b>Phone Number</b></label>
<input type="text" placeholder="Enter Phone Number" [(ngModel)]="phoneNumber" name="phoneNumber" required>
<button (click)="myFunc()">NEXT</button>
</div>
</form>
I'm trying to create charge using a token created with stripe elements on the front end. I want to add the customers address by binding the different properties of tokenData with ngmodel to inputs, then passing the tokenData object as the second argument of the createToken() method.
//component.html
<input type="text" [(ngModel)]="name" placeholder="name" name="name">
<input type="text" [(ngModel)]="address_line1" placeholder="adress line 1" name="address">
<input type="text" [(ngModel)]="address_line2" placeholder="adress line 2" name="address">
<input type="text" [(ngModel)]="address_city" placeholder="City" name="city">
<input type="text" [(ngModel)]="address_state" placeholder="State" name="state">
<input type="text" [(ngModel)]="address_country" placeholder="Country" name="country">
<button (click)="submitForm()">Submit Payment</button>
//component.ts
public tokenData = {
name: '',
address_line1: '',
address_line2: '',
address_city: '',
address_state: '',
address_zip: undefined,
address_country: ''
};
public submitForm = () => {
this.stripe.createToken(this.card, this.tokenData).then(res => {
if(res.error){
console.log(res.error.message);
}
else {
this.stripeTokenHandler(res.token).subscribe();
console.log(res.token);
}
});
};
public stripeTokenHandler(t){
return this.http.post(`${this.apiUrl}/charge`, t);
};
but when I submit the form the token gets logged to the console with the tokenData parameters empty, which means that the inputs aren't getting binding properly to tokenData. How can this be done?
You are not binding to the properties of the tokenData, add tokenData to all your bindings like [(ngModel)]="tokenData.address_line1"
<input type="text" [(ngModel)]="tokenData.name" placeholder="name" name="name">
<input type="text" [(ngModel)]="tokenData.address_line1" placeholder="adress line 1" name="address">
<input type="text" [(ngModel)]="tokenData.address_line2" placeholder="adress line 2" name="address">
<input type="text" [(ngModel)]="tokenData.address_city" placeholder="City" name="city">
<input type="text" [(ngModel)]="tokenData.address_state" placeholder="State" name="state">
<input type="text" [(ngModel)]="tokenData.address_country" placeholder="Country" name="country">
I'm a newbie to angular, so I need a help.
In html, I wrote the following
<div class="form-group">
<input type="email" name="Email" id="LoginEmail class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
In angular, I write the following code
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [
{name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"}
];
}]);
I need to compare the value of input box with the value of the script and show a message if it's not correct, so how can I do that?
Firstly you need to assign model to your template scope. Use ng-model for this purpose. Then you need a form to submit and trigger a function to check if user input matches to the desired values.
Add ng-model and wrap your inputs with a form tag:
<form ng-submit="login()">
<div class="form-group">
<input ng-model="email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
<button type="submit">Login</button>
</form>
Check if user input is valid in Controller:
$scope.login = function() {
const isUserValid = $scope.email === $scope.userinfo[0].account && $scope.password === $scope.userinfo[0].password;
if(isUserValid) {
alert("Logged In Successfully");
}else {
alert("Email or password incorrect. Try again.")
}
}
Here's a working example of the above code.
In your input elements you miss the ng-model attribute. It is used to bind the values with your scope variables.
<input type="email" ... ng-model="email" ...>
<input type="password" ... ng-model="password" ...>
And in your controller you can write
if($scope.email == $scope.userinfo[0].account && $scope.password == $scope.userinfo[0].password){
//Login ok
}else{
//Login failed
}
Assuming there is a form element somewhere above
Add ng-submit to it
<form ng-submit="submit()">
Add ng-model to the form elements.
I have added state.email and state.password
<div class="form-group">
<input ng-model="state.email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="state.password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
Compare the binding values to the values in $scope.userinfo
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [{
name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"
}];
// when you submit the form, this function will be called
$scope.submit = function (e) {
e.preventDefault();
if ($scope.state.email !== $scope.userinfo[0].account || $scope.state.password !== $scope.userinfo[0].password) {
// did not match
} else {
// matched
}
}
}]);
I would like to do a simple base where I can add memebers to array. I change a "Tour of Heroes" from Angular tutorial (link). What I want to do is instead of passing name (string) to function I would like to give a whole class object (User). I use form where user is typing his name and surname (and city if he want). I have no idea how to get from input to function this whole object, instead of list of string parameters. Here is my code:
form.html:
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="Name" required name="nameField" [(ngModel)]="ngModel" #nameField="ngModel" >
<div [hidden]="nameField.valid || nameField.pristine" class="alert alert-danger">Name is required</div>
</div>
<div class="form-group">
<label for="surname">surname</label>
<input type="text" class="form-control" id="surname" required name="surnameField" ngModel #surnameField="ngModel">
<div [hidden]="surnameField.valid || surnameField.pristine" class="alert alert-danger">Surname is required</div>
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" class="form-control" id="city" name="city" ngModel #cityField="ngModel" >
</div>
<button type="submit" class="btn btn-success" [disabled]="!userForm.form.valid">Submit</button>
</form>
function on submit:
onSubmit(name: string, surname: string, city: string ): void{
name = name.trim();
surname = surname.trim();
city = city.trim();
this.myservice.create(name, surname, city)
.then(newUser => this.arrayUsers.push(newUser));
}
And function create inside myservice:
private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = 'api/mainArray'; // URL to web api
create(name: string, surname: string, city?: string): Promise<User> {
return this.http
.post(this.heroesUrl, JSON.stringify({name: name, surname:surname, city:city}), {headers: this.headers})
.toPromise()
.then(res => res.json().data as User);
}
Declare the ngModel attribute to bind each input to the form :
For example :
<input type="text" class="form-control" id="name" ngModel required name="nameField" >
<input type="text" class="form-control" id="surname" ngModel required name="surnameField" >
<input type="text" class="form-control" id="city" ngModel required name="cityField" ngModel >
And in the form element, give a name to the form to be able to bind it in the component and add the form as parameter in the onSubmit() method :
<form #f="ngForm" (ngSubmit)="onSubmit(f)" >
Now you should be able to retrieve the user with the f.value property :
onSubmit(f: NgForm): void{
this.myservice.create(f.value)
.then(createdUser=> this.arrayUsers.push(createdUser));
}
More information here : https://angular.io/api/forms/NgModel
Please help me to check this part of code.
<body ng-app = "myApp">
<h1>FORM </h1>
<div ng-controller="myController">
<p><label>Username : </label><input type="text" ng-model="user.username" name="username" id="username" /></p>
<p><label>Email : </label><input type="email" ng-model="user.email"/></p>
<p><label>Verifikasi Email : </label><input type="email" ng-model="user.verify_email" /></p>
<p><label>Password : </label><input type="password" ng-model="user.password" id="password" /></p>
<button type="button" ng-click = "add()" >Sig In</button>
</div>
</body>
In my Javascript:
<script>
var app = angular.module('myApp', []);
app.controller("myController", function($scope){
$scope.user = {};
$scope.add = function(){
$scope.data = [
{ nama : $scope.user.username},
{ email : $scope.user.email},
{password : $scope.user.password } ];
console.log($scope.data);
}
});
Thanks for you all. I already update my script. When I click the button, the console didn't print the data. Why? I think there is something wrong.
You didn't define user
But that shouldn't be the problem if you use only user as model like
<input type="text" ng-model="user" name="username" id="username" />
It'll be added as property in the scope without any worries.
But you have added property username in user.
As user is undefined so the scenario will be undefined.username which is not permitted.
Try to defined user as object then any property will automically added.
Like this
$scope.user={};
in your HTML you should
<body ng-app = "myApp">
<div ng-controller="myController">
<p><label>Username : </label><input type="text" ng-model="user.username" name="username" id="username" /></p>
<p><label>Email : </label><input type="email" ng-model="user.email"/></p>
<p><label>Verifikasi Email : </label><input type="email" ng-model="user.verify_email" /></p>
<p><label>Password : </label><input type="password" ng-model="user.password" id="password" /></p>
<button type="button" ng-click = "add(user)" >Sig In</button>
</div>
</body>
in case of
ng-click = "add()"
use
ng-click = "add(user)"
in your controller
$scope.add = function(user){
$scope.data = [
{ name : user.username},
{ email : user.email},
{password : user.password }
];
console.log($scope.data);
}); // End add Function