升级到最终后,angular2动态验证消息不起作用

时间:2016-11-11 04:38:03

标签: angular angular2-forms

我自定义动态验证Angular2.RC4中的表单消息(验证表单而不在每个输入定义错误消息)

ChangePass.ts

@Component({
    selector: '[change-password]',
    template: `<form [ngFormModel]="passwordForm" id="passwordForm" (ngSubmit)="changePassword()">
        <div class="row">
            <div class="input-field col s12">
                <input type="password" class="form-control" id="oldPassword" ngControl="oldPassword" [(ngModel)]="model.oldPassword">
                <label for="oldPassword">Current Password</label>
                <control-messages control="oldPassword"></control-messages>
            </div>
        </div>
    </form>`,
    directives: [ControlMessages],
})
export class ChangePasswordComponent {
    formBuilder;

    constructor(myElement:ElementRef, formBuilder:FormBuilder) {
        this.formBuilder = formBuilder;
        this.passwordForm = this.formBuilder.group({
            oldPassword: ['', Validators.required]
        });
    }
}

ControlMessages.ts

import {Component, Host} from '@angular/core';
import {NgFormModel} from '@angular/common';
@Component({
    selector: 'control-messages',
    inputs: ['controlName: control'],
    template: `<div *ngIf="errorMessage !== null">{{errorMessage}}</div>`
})
export class ControlMessages {
    controlName:string;

    constructor(@Host() private _formDir:NgFormModel) {
        this.helper = helper;
    }

    get errorMessage() {
        let formControls = this._formDir.form;
        let control = formControls.find(this.controlName);

        if (control) {
            //do something
        }
        return null;
    }
}

当我升级到Angular2决赛。
我将[ngFormModel]更改为[formGroup],将ngControl更改为formControlName。 在ControlMessages组件中,我无法通过controlName获取formControls来查找control 我该怎么办?

1 个答案:

答案 0 :(得分:2)

根据angular 2最终版本,你不能在directives decorator.Add ControlMessagesComponent中使用@Component来模块声明并在ControlMessages指令下使用:

import { Component, Host, Input } from '@angular/core';
import { FormGroupDirective } from '@angular/forms';

@Component({
  selector: 'control-messages',
  template: `<div class="form-error" *ngIf="errorMessage !== null">{{errorMessage}}</div>`
})
export class ControlMessagesComponent {
  @Input() public controlName: string;

  constructor(@Host() private _formDir: FormGroupDirective) {
  }

  get errorMessage() {
    // Find the control in the Host (Parent) form
    let allControls = this._formDir.form.controls;

    let c = allControls.hasOwnProperty(this.controlName) ? allControls[this.controlName] : null;
    if (c !== null) {
      //do something
    }
    return null;
  }
}