简体   繁体   English

Angular2:例外:在控件上找不到指令注释

[英]Angular2 : EXCEPTION: No Directive annotation found on Control

I am building a custom input field component with custom validations such as decimal only numbers, minimum, maximum, etc. Later i will reuse it in various form throughout my application. 我正在使用自定义验证构建自定义输入字段组件,例如仅十进制数字,最小值,最大值等。稍后,我将在整个应用程序中以各种形式重用它。

Following is the sample code of the custom input component: 以下是自定义输入组件的示例代码:

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);
}

Application crashes with massage: "EXCEPTION: No Directive annotation found on Control". 应用程序崩溃并显示警告:“例外:在Control上找不到指令注释”。

I have googled various tutorials on Angular2 forms where they use the similar approach but input element is inside a form with temporary local variable for the given input is set to ngForm, as shown below: 我在Angular2表单上搜索了各种教程,在其中使用了类似的方法,但是input元素位于具有临时局部变量的表单内,该表单的给定输入设置为ngForm,如下所示:

ngControl="test"
#test = "ngForm"

My question is that, is it possible to use ngControl in input component without a form? 我的问题是,是否可以在没有格式的输入组件中使用ngControl? yes then how to fix the exception? 是的,那么如何解决异常?

I m using Angular 2 - RC1 with material2. 我在材质2中使用Angular 2-RC1。

Control is not a directive, the directive you are looking for is NgFormControl . Control不是指令,您要查找的指令是NgFormControl So: 所以:

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);
}

Here is a plunk 这里是一个普拉克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM