我正在使用angular5,表单如下:
<div class="box-body">
<form novalidate #formRef="ngForm">
<div class="row">
<div class="col-sm-6 form-group">
<label>First name</label>
<input type="text" class="form-control" name="firstName" ngModel #firstNameRef="ngModel">
</div>
<div class="col-sm-6 form-group">
<label>Last name</label>
<input type="text" class="form-control" name="lastName" ngModel #lastNameRef="ngModel">
</div>
</div>
<button type="submit" class="btn btn-secondary" (ngSubmit)="onSubmit(formRef.value)">Submit</button>
</form>
</div>
该课程如下:
import { Component } from '@angular/core';
interface User {
firstName: string;
lastName: string;
}
@Component({
selector: "registration-form",
templateUrl: "./registration-form.component.html"
})
export class RegistrationFormComponent {
onSubmit(formValue) {
alert('hi')
console.log(formValue);
}
}
但是当我在输入中填充数据时,并没有提交任何控制台。以及根本没有召唤的警报。什么错过了?任何人帮助我
答案 0 :(得分:2)
您必须在此(ngSubmit)
标记中指定<form>
事件(不在按钮中):
<div class="box-body">
<form novalidate #formRef="ngForm" (ngSubmit)="onSubmit(formRef.value)">
<div class="row">
<div class="col-sm-6 form-group">
<label>First name</label>
<input type="text" class="form-control" name="firstName" ngModel #firstNameRef="ngModel">
</div>
<div class="col-sm-6 form-group">
<label>Last name</label>
<input type="text" class="form-control" name="lastName" ngModel #lastNameRef="ngModel">
</div>
</div>
<button type="submit" class="btn btn-secondary">Submit</button>
</form>
</div>
答案 1 :(得分:0)
它对我有用:
<div class="box-body" >
<form novalidate #formRef="ngForm" (ngSubmit)="onSubmit(formRef.value)">
<div class="row">
<div class="col-sm-6 form-group">
<label>First name</label>
<input type="text" class="form-control" name="firstName" ngModel #firstNameRef="ngModel">
</div>
<div class="col-sm-6 form-group">
<label>Last name</label>
<input type="text" class="form-control" name="lastName" ngModel #lastNameRef="ngModel">
</div>
</div>
<button type="submit" class="btn btn-secondary">Submit</button>
</form>
</div>