在Angular 2中,要添加带验证支持的Bootstrap表单,可以按照以下步骤进行操作:
npm install bootstrap@4.0.0-alpha.6 --save
npm install jquery --save
npm install tether --save
angular-cli.json
文件中,将Bootstrap的CSS和JavaScript文件添加到styles
和scripts
数组中:"styles": [
"styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/tether/dist/js/tether.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js"
],
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
ngOnInit
生命周期钩子中初始化它:export class MyComponent {
myForm: FormGroup;
ngOnInit() {
this.myForm = new FormGroup({
name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', Validators.minLength(6))
});
}
}
<form [formGroup]="myForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" formControlName="name">
<div *ngIf="myForm.controls.name.invalid && myForm.controls.name.touched" class="alert alert-danger">
Name is required.
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" formControlName="email">
<div *ngIf="myForm.controls.email.invalid && myForm.controls.email.touched" class="alert alert-danger">
Email is required and must be a valid email address.
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" formControlName="password">
<div *ngIf="myForm.controls.password.invalid && myForm.controls.password.touched" class="alert alert-danger">
Password must be at least 6 characters long.
</div>
</div>
<button type="submit" class="btn btn-primary" [disabled]="myForm.invalid">Submit</button>
</form>
在上述代码中,我们使用了formGroup
指令将表单对象与表单元素关联起来,使用formControlName
指令将表单控件与表单对象中的属性关联起来。同时,使用了Bootstrap的样式类来美化表单。
这样,就完成了在Angular 2中添加带验证支持的Bootstrap表单的操作。
关于腾讯云相关产品和产品介绍链接地址,由于要求不能提及具体的云计算品牌商,建议您参考腾讯云官方文档或咨询腾讯云的客服人员,以获取更详细的信息。
领取专属 10元无门槛券
手把手带您无忧上云