2

我正在为 Angular 2 使用材料的 md-input 组件。我知道它仍然是材料的 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>

我如何使用“必需”?

<md-hint *ngIf="url.errors.required && (url.dirty || url.touched)" [ngStyle]="{'color': 'red'}"> Url is required </md-hint>
4

1 回答 1

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>
于 2016-12-13T21:26:07.120 回答