Angular 2子组件无法获取父组件

时间:2016-03-28 08:49:36

标签: angular angular2-directives angular2-forms angular2-formbuilder

我正在尝试make a component,它将显示给定控制输入名称的特定错误消息。 这是我的代码......

register.ts:

import { Component } from 'angular2/core';
import { FormBuilder, Validators } from 'angular2/common';
import {ControlMessages} from './control-msg';
@Component({
    selector: 'registration-form',
    templateUrl: './app/components/registration/registration.html',
    directives: [ControlMessages]
})

控制msg.ts:

import {Component, Host} from 'angular2/core';
import {NgFormModel,FORM_PROVIDERS} from 'angular2/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){/* _formDir doesn't get the parent object! */}

    get errorMessage() {
        // Find the control in the Host (Parent) form
        let c = this._formDir.form.find(this.controlName);
        return null;
    }
}

问题是,您可以看到ControlMessages无法获取我的父NgFormModel的值。

Angular 2向我显示了这个错误,

  

EXCEPTION:没有NgFormModel的提供者! (ControlMessages - &gt; NgFormModel)

如果我在ControlMessages中包含NgFormModel作为提供者,那么它会向我显示此错误,

  

EXCEPTION:TypeError:在[errorMessage!== null in ControlMessages @ 0:5]中无法读取null的属性'find'

请注意,我在引导应用时没有注入任何提供商 我正在使用 angular2 beta 12

修改

表单模板:

<div class="form-group" 
     [class.has-error]="!registerForm.find('username').valid && registerForm.find('username').dirty">
  <label for="username">Username</label>
  <input type=text id="username" class="form-control" placeholder="username" 
         [ngFormControl]="registerForm.find('username')">
  <control-messages control="username"></control-messages>
</div>

1 个答案:

答案 0 :(得分:1)

ControlMessages组件嵌套在div中。这就是为什么它没有得到父对象的原因。

表单模板应该是这样的:

<form [ngFormModel]="registerForm" (ngSubmit)="onSubmit()">

  <div class="form-group" 
       [class.has-error]="!registerForm.find('username').valid && registerForm.find('username').dirty">
    <label for="username">Username</label>
    <input type=text id="username" class="form-control" placeholder="username" 
           [ngFormControl]="registerForm.find('username')">
  </div>

  <control-messages control="username"></control-messages>

  <button type="submit" class="btn btn-primary"
          [disabled]="!registerForm.find('username').valid">Register</button>

</form>