Here is my HTML code:
<form>
<input id = "username" type="text" name="username" ngModel placeholder="username">
<input id = "password" type="password" name="password" ngModel placeholder="password">
</form>
<button name="buttonLogin" type="button" (click)="login()" style="height:30px; width:100px;">Login</button>
Here is my component.ts file code:
export class AuthComponent implements OnInit {
username: any;
password: any;
login(){
this.authService.login(this.username,this.password).subscribe(data=>console.log('login
successful'));//email pass will be fetched from text boxes
}
}
I have tried many ways to get input from the text field into the component.ts file variables. but no method works. I am working on frontend as well as backend. This is the authorization part. If i pass username
and password
values directly in the component.ts file then the login is successful all the way to the backend and the database. But when I try to get variables of the input text fields in the html file then it doesn't work.
Please have a look, thanks.
CodePudding user response:
Hey there are two ways to make forms in angular :
- Reactive forms
With this method, you have to define your properties like this :
export class AuthComponent implements OnInit {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
username: ['default value', [/*Validators*/]]
password: ['default value', [/*Validators*/]]
})
}
login(){
this.authService.login(this.myForm.value.username,this.myForm.value.password).subscribe(data=>console.log('login
successful'));//email pass will be fetched from text boxes
}
}
and then you can use it as below :
<form [formGroup]="myForm">
<input id = "username" formGroupName="username" type="text" name="username" placeholder="username">
<input id = "password" formGroupName="password" type="password" name="password" placeholder="password">
</form>
<button name="buttonLogin" type="button" (click)="login()" style="height:30px; width:100px;">Login</button>
- Template-driven forms
With this method, you have to bind your input thanks to the [(ngModel)]
property :
<input type="text" id="username"
required
[(ngModel)]="username" name="username">
If needed, you can check the doc about forms in angular :)
Reactive form : https://angular.io/guide/reactive-forms
Template driven form : https://angular.io/guide/forms
PS : The click event on the submit button is working but the correct way to build a form is to set a (submit) event on the form and a button with type="submit" :)
CodePudding user response:
Use Two way binding to get the values for username, password.
<form>
<input id = "username" type="text" name="username" [(ngModel)]="username" placeholder="username">
<input id = "password" type="password" name="password" [(ngModel)]="password" placeholder="password">
</form>
Also refer to Angular forms documentation to find more information and types of forms. https://angular.io/guide/forms-overview