如何在Angular 2中的无效字段上显示“具有错误”类

Bac*_*tnz 5 javascript angular

鉴于:

<div class="form-group" [fieldValidity]="email">
  <label for="email" class="sr-only">Email</label>
  <input [(ngModel)]="model.email" ngControl="email" required>
</div>
Run Code Online (Sandbox Code Playgroud)

我的自定义[fieldValidity]指令:

import { Directive, ElementRef, Input } from 'angular2/core';
import {NgControlName} from 'angular2/common';
@Directive({
  selector: '[fieldValidity]'
})
export class FieldValidityDirective {
  private el: HTMLElement;
  @Input('fieldValidity') field: NgControlName;
  constructor(el: ElementRef) { 
    this.el = el.nativeElement;
  }
  private _onValidityChange(value: string) {
    //TODO test field.valid || field.pristine
    if (?) { 
      this.el.classList.remove('has-error');
    } else {
      this.el.classList.add('has-error');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我如何订阅field.valid && field .pristine值以显示错误?(我在下面用“ TODO”标记了它)

Dom*_*nic 6

一种简单的方法是将数据驱动方法与[ngClass]指令一起使用,如下所示

模板:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <div [ngClass]="{'has-error': form.controls['description'].invalid}">
            <input type="text" formControlName="description" class="form-control" required [(ngModel)]="description">
        </div>
    </div>
    <button type="submit" class="btn btn-success">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

零件:

export class FormComponent implements OnInit {

  private form: FormGroup;
  private description: string;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.form = this.formBuilder.group({
      description: new FormControl('')
    });
  }
}
Run Code Online (Sandbox Code Playgroud)


Thi*_*ier 3

您还可以实现该ngDoCheck方法来检查有效性:

ngDoCheck(value: string) {
  if (field.valid || field.pristine) { 
    this.el.classList.remove('has-error');
  } else {
    this.el.classList.add('has-error');
  }
}
Run Code Online (Sandbox Code Playgroud)

也就是说,您可以实现一个ngClass直接利用该元素的包装组件。像这样的东西:

@Component({
  selector: 'field',
  template: `
    <div class="form-group form-group-sm" [ngClass]="{'has-error':state && !state.valid}">
      <label for="for" class="col-sm-3 control-label">{{label}}</label>
      <div class="col-sm-8">
        <!-- Input, textarea or select -->
        <ng-content></ng-content>
        <span *ngIf="state && !state.valid" class="help-block text-danger">
          <span *ngIf="state.errors.required">The field is required</span>
        </span>
    </div>
  </div>
`
})
export class FormFieldComponent {
  @Input()
  label: string;

  @Input()
  state: Control;
}
Run Code Online (Sandbox Code Playgroud)

ng-content您甚至可以通过使用装饰器直接引用控件来更进一步@ContentChild:

@Component({
  (...)
})
export class FormFieldComponent {
  @Input()
  label: string;

  @ContentChild(NgFormControl) state;

  (...)
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以用这种方式定义你的输入ngFormControl(也可以使用ngControl):

<form [ngFormModel]="companyForm">
  <field label="Name">
    <input [ngFormControl]="companyForm.controls.name" 
           [(ngModel)]="company.name"/>
  </field>
</form>
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅本文(“字段的表单组件”部分):