[英]How to pass variable of text field of html to typescript in Angular?
这是我的 HTML 代码:
<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>
这是我的 component.ts 文件代码:
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
}
}
我已经尝试了很多方法来将文本字段的输入输入到 component.ts 文件变量中。 但没有任何方法有效。 我正在从事前端和后端工作。 这是授权部分。 如果我直接在 component.ts 文件中传递username
和password
值,那么登录一直成功到后端和数据库。 但是当我尝试获取 html 文件中输入文本字段的变量时,它不起作用。 请看一下,谢谢。
嘿有两种方法可以在 angular 中制作 forms:
使用此方法,您必须像这样定义属性:
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
}
}
然后你可以使用它如下:
<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>
使用此方法,由于[(ngModel)]
属性,您必须绑定输入:
<input type="text" class="form-control" id="username"
required
[(ngModel)]="username" name="username">
如果需要,您可以在angular中查看有关forms的文档:)
反应形式: https://angular.io/guide/reactive-forms
模板驱动表单: https://angular.io/guide/forms
PS:提交按钮上的点击事件有效,但构建表单的正确方法是在表单上设置一个(提交)事件和一个类型为“提交”的按钮:)
使用双向绑定获取用户名和密码的值。
<form>
<input id = "username" type="text" name="username" [(ngModel)]="username" placeholder="username">
<input id = "password" type="password" name="password" [(ngModel)]="password" placeholder="password">
</form>
另请参阅 Angular forms 文档以查找 forms 的更多信息和类型。 https://angular.io/guide/forms-overview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.