我最近一直在玩Angular 2表格,特别是表单验证。 以下3个文件是我的代码的一部分:app.component,app.component.html和hide-valid.directive
app.component.ts
import { Component, OnInit } from '@angular/core';
import { REACTIVE_FORM_DIRECTIVES, FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: 'app/templates/app.component.html',
directives: [REACTIVE_FORM_DIRECTIVES],
providers: [FormBuilder]
})
export class AppComponent {
loginForm: FormGroup;
username: FormControl;
password: FormControl;
constructor(builder: FormBuilder) {
this.username = new FormControl('', [
Validators.required,
Validators.maxLength(3)
]);
this.password = new FormControl('', Validators.required);
this.loginForm = builder.group({
username: this.username,
password: this.password
});
}
onSubmit() {}
}
隐藏-valid.directive.ts
import { Input, OnInit, Directive, ElementRef, Renderer } from '@angular/core';
import { FormControl } from '@angular/forms';
@Directive({
selector: '[hide-valid]'
})
export class HideValidDirective {
valid: Boolean;
@Input() set isValid(property: FormControl) {
this.valid = property.untouched || property.valid;
this.set();
}
constructor(
private el: ElementRef,
private renderer: Renderer) {
}
set() {
if (this.valid) {
this.renderer.setElementStyle(this.el.nativeElement,
'display', 'none');
}
}
}
app.component.html
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<label for="username">username</label>
<input type="text" name="username" id="username" [formControl]="username">
<div [hidden]="username.valid || username.untouched">
<span *ngIf="username.hasError('required')">Field is required</span>
<span *ngIf="username.hasError('maxlength')">Field is limited to 3 characters.</span>
</div>
<button type="submit">log in</button>
</form>
我想要做的是替换这段代码:
<div [hidden]="username.valid || username.untouched">
<span *ngIf="username.hasError('required')">Field is required</span>
<span *ngIf="username.hasError('maxlength')">Field is limited to 3 characters.</span>
</div>
进入这个:
<div hide-valid isValid="{{ username }}">
<span *ngIf="username.hasError('required')">Field is required</span>
<span *ngIf="username.hasError('maxlength')">Field is limited to 3 characters.</span>
</div>
但问题是如果我使用这种语法,我无法访问用户名上的任何属性。在我的isValid(property:any)属性中,[object object]
我错过了什么?我发现第二种语法比第一种解决方案更好更短,这就是我使用该指令的原因。
答案 0 :(得分:0)
{{...}}
用于字符串插值。它在赋值之前对每个值进行字符串化。
改为使用
<div hide-valid [isValid]="username">
您也可以将选择器更改为[isValid]
,然后将代码缩短为
<div [isValid]="username">