2016-05-15 23 views
0

我正在構建一個自定義輸入字段組件,其中包含自定義驗證,例如只包含小數的數字,最小值,最大值等。稍後我會在整個應用程序中以各種形式重用它。Angular2:EXCEPTION:在控件上找不到指令註釋

以下是定製輸入分量的採樣代碼:

import { Component } from '@angular/core'; 
import {MD_INPUT_DIRECTIVES} from '@angular2-material/input'; 
import {Control, Validators} from '@angular/common'; 

@Component({ 
    selector: 'test', 
    template: `<md-input 
       placeholder="test" 
       ngControl="test" 
       id = "test"      
       required> 
       <md-hint *ngIf="!test.valid">Not a valid input</md-hint> 
      </md-input>`, 
    directives: [MD_INPUT_DIRECTIVES, Control] 
}) 
export class TestComponent { 
    test = new Control('',Validators.required); 
} 

應用崩潰,並按摩:「例外:無上控制找到指令註釋」。

我已在其中它們使用類似的方法,但輸入元件是具有用於給定的輸入被設置爲ngForm,臨時局部變量形式內Angular2形式一派各種教程,如下所示:

ngControl="test" 
#test = "ngForm" 

我問題是,是否可以在沒有表單的情況下在輸入組件中使用ngControl?是的,那麼如何解決這個異常?

我使用Angular 2 - RC1和material2。

回答

1

Control不是一個指令,你正在尋找的指令是NgFormControl。所以:

import {Control,NgFormControl, Validators} from '@angular/common'; 

@Component({ 
    ... 
    template: `<md-input 
       placeholder="test" 
       [ngFormControl]="test" 
       id = "test"      
       required> 
       <md-hint *ngIf="!test.valid">Not a valid input</md-hint> 
      </md-input>`, 
    directives: [MD_INPUT_DIRECTIVES, NgControl] 
}) 
export class TestComponent { 
    test = new Control('',Validators.required); 
} 

這裏是一個plunk

+0

完美..謝謝 – ravi