使用功能角度输入值时出现问题

时间:2019-04-24 16:36:14

标签: angular function variables input

我正在使用angular创建学校项目的登录表单,html如下所示:

<input type="text" ng-model="username" name="username" />
<input type="text" ng-model="password" name="password" />
<button (click)="submit(username, password)">Login</button>

我在与此组件相关联的打字稿文件中定义了Submit函数,当我尝试运行该函数时,由于未正确定义变量,我收到了错误消息。 我的目标是从登录名和密码部分中获取输入文本,并在按下按钮时将其插入到Submit函数中,我以为ng-model定义可以做到这一点,但是我对angular还是陌生的,所以我必须做点什么错误的。

5 个答案:

答案 0 :(得分:0)

我猜您正在使用Angular(2+),而不是AngularJS(1.x)。如果是这种情况,则应使用ngModel而不是ng-model

答案 1 :(得分:0)

在表单标签中使用您的输入,

<form (ngSubmit)="onSubmit()">
<input type="text" [(ngModel)]="username" name="username" />
<input type="text" [(ngModel)]="password" name="password" />
<button class="submit-button" type="submit">Submit</button>

答案 2 :(得分:0)

使用[(ngModel)]。它将每个输入分别绑定到usernamepassword

答案 3 :(得分:0)

我将带上您在问题中添加的标签(Angular 2 +)。

在HTML上使用ngModel的方式是这样的:

<input type="text" [(ngModel)]="username" name="username" />
<button (click)="submit()">Login</button>

您需要导入Forms Module才能使用ngModel

在您的TS文件中:

username: string;

submit(){
    //do whatever you want accessing the variable this way: this.username
}

您可以使用表格,但这在其他答案中有所说明。

答案 4 :(得分:0)

<input type="text" [(ngmodel)]="username" name="username">
<input type="text" [(ngmodel)]="password" name="password">
<button (click)="submit()">Login</button>

在component.ts中,首先定义双向绑定的字段

public username:any;
public password:any

在提交功能中

submit(){
//call fields 
this.username
this.password
}

我希望您将表格模块导入appmoodule(根模块)