我正在读阿里·勒纳的书ng-book
在 Angular 5 上。我正在使用ngx-bootstrap
and Bootstrap 4
。表单验证似乎并不像勒纳先生实现的那样工作。我不确定这是否是一个限制ngx-bootstrap
……有人知道吗?
edit好的,我删除了ngx-bootstrap
并刚刚加载了 MaxCDNBootstrap 4
我也有同样的问题。错误消息没有出现。
应用程序模块.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { RegistrationFormComponent } from './registration-form/registration-form.component';
import {
FormsModule,
ReactiveFormsModule,
FormBuilder,
FormGroup
} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
RegistrationFormComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
注册表格.component.ts
import { Component, OnInit } from '@angular/core';
import {
FormBuilder,
FormGroup,
Validators
} from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './registration-form.component.html',
styleUrls: ['./registration-form.component.scss']
})
export class RegistrationFormComponent implements OnInit {
regForm: FormGroup;
// name: AbstractControl;
constructor(fb: FormBuilder) {
this.regForm = fb.group({
'name': ['', Validators.required],
// 'email': ['', Validators.required],
// 'password': ['', Validators.required],
// 'password_confirmation': ['', Validators.required]
});
// this.name = this.regForm.controls['name'];
}
ngOnInit() {
}
onSubmit(value: string): void{
console.log(value);
}
}
注册表格.component.html
<div class="row justify-content-center">
<h1>New User</h1>
</div>
<div class='row justify-content-center'>
<div class='col-6'>
<form [formGroup]='regForm'
(ngSubmit)="onSubmit(regForm.value)"
[class.error]="!regForm.valid && regForm.touched"
>
<div class='form-group'
[class.error]="!regForm.get('name').valid && regForm.get('name').touched">
<label>Name</label>
<input type="text" class='form-control' [formControl]="regForm.controls['name']">
<div *ngIf="regForm.controls['name'].hasError('required')" class="invalid-feedback">Name is required</div>
</div>
<div class='form-group'>
<label>Email</label>
<input type="email" class='form-control'>
</div>
<div class='form-group'>
<label>Password</label>
<input type="password" class='form-control'>
</div>
<div class='form-group'>
<label>Confirmation</label>
<input type="password" class='form-control'>
</div>
<button type="submit" class='btn btn-default'>Submit</button>
</form>
</div>
</div>