我正在制作一个角度为2的小SPA,现在我正在处理表单验证。 阅读本教程:https://angular.io/docs/ts/latest/guide/forms.html。我已经用简单的验证完成了一个简单的表单。这是我的代码:
英雄(模特)
export class Hero{
// Name of hero.
email: string;
// Password of hero.
password: string;
}
嵌件英雄card.component.ts
import {Component, EventEmitter} from "@angular/core";
import {Hero} from '../models/hero.model';
@Component({
selector: 'insert-hero-card',
templateUrl: 'app/components.template/insert-hero-card.html',
outputs: ['insertHero']
})
export class InsertHeroCardComponent{
// Information of hero stored here.
hero: Hero;
// This emitter is used for raising event when a hero is confirmed being inserted.
insertHero : EventEmitter<Hero>;
// Initialize component with settings.
constructor(){
this.hero = new Hero();
this.hero.email = "A";
this.hero.password = "ThisIsPassword";
this.insertHero = new EventEmitter<Hero>();
}
// This event is fired when ok button is clicked.
heroConfirmInsert(): void {
//this.insertHero.emit(this.hero);
}
}
插入英雄-card.html
<form class="panel panel-primary"
#insertHeroCardControl="ngForm">
<div class="panel-heading">
<span>Hero</span>
</div>
<div class="panel-body">
<div class="col-lg-12">
<!-- Hero name -->
<div class="row">
<div class="col-lg-3">
<span class="control-label">Email</span>
</div>
<div class="col-lg-9">
<input class="form-control"
[(ngModel)]="hero.email"
required
#heroEmail="ngModel"
name="heroEmail"/>
<div class="alert alert-info"
[hidden]="heroEmail.valid">Hero name is required</div>
</div>
</div>
<br/>
<!-- Hero hp -->
<div class="row">
<div class="col-lg-3">
<span class="control-label">Hp</span>
</div>
<div class="col-lg-9">
<input class="form-control"
type="password"
[(ngModel)]="hero.password"
name="heroPassword"/>
</div>
</div>
<br/>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-primary"
(click)="heroConfirmInsert()">Ok</button>
</div>
</form>
在我的代码中,我使用 heroEmail.valid 来显示/隐藏名称需要验证。我想知道是否可以手动将有效设置为true / false。因为在我的后端服务中,我可以返回这样的模型:
{
email: [
"required",
"maxlength",
"minlenth"
]
}
如果有办法设置对model.errors的响应,我可以在服务端使用客户端迁移验证,而无需重写代码。
有人能帮帮我吗?
谢谢,