Reputation: 21
I'm using the md-input component of material for Angular 2. I know it's still a alpha version of material but maybe someone could explain me how to use the html validation attribute required of Angular 2 with md-input(Is it implemented yet?). I have tried this(works fine):
<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>
How I can use 'required'?
<md-hint *ngIf="url.errors.required && (url.dirty || url.touched)" [ngStyle]="{'color': 'red'}"> Url is required </md-hint>
Upvotes: 2
Views: 7348
Reputation: 9678
In your TS file you should have :
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..
}
And change your HTML to :
<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>
Upvotes: 2