我正在使用Angular 2的材质的md输入组件。我知道它仍然是材料的alpha版本,但也许有人可以解释我如何使用Angular 2所需的html验证属性用md-input(它实现了吗?)。我试过这个(工作正常):
<md-card>
<md-input
placeholder="Url"
id="url"
url="url"
[(ngModel)]="urlInputValue"
#url="ngModel"
required>
<md-hint *ngIf="url.errors && (url.dirty || url.touched)" [ngStyle]="{'color': 'red'}"> Url is required </md-hint>
</md-input>
<button
md-raised-button color="accent"
[disabled]="isUrlInputEmpty()"
(click)="onRequestBtnClick()">
Request
</button>
</md-card>
我如何使用&#39; required&#39;?
<md-hint *ngIf="url.errors.required && (url.dirty || url.touched)" [ngStyle]="{'color': 'red'}"> Url is required </md-hint>
答案 0 :(得分:2)
在您的TS文件中,您应该:
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
export class UrlComponent {
public urlForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.urlForm = this.formBuilder.group({
url: new FormControl('', Validators.required),
});
}
//... codes..
}
将您的HTML更改为:
<form role="form" [formGroup]="urlForm" novalidate>
<md-input
placeholder="Url"
id="url"
url="url"
[(ngModel)]="urlInputValue"
formControlName="url"
#url="ngModel"
>
<md-hint *ngIf="url.errors && (url.dirty || url.touched)" [ngStyle]="{'color': 'red'}"> Url is required </md-hint>
</md-input>
<button
md-raised-button color="accent"
[disabled]="isUrlInputEmpty()"
(click)="onRequestBtnClick()">
Request
</button>
</form>