【问题标题】:Angular2 : EXCEPTION: No Directive annotation found on ControlAngular2:例外:在控件上找不到指令注释
【发布时间】:2016-09-11 15:39:39
【问题描述】:

我正在构建一个带有自定义验证的自定义输入字段组件,例如仅十进制数字、最小值、最大值等。稍后我将在整个应用程序中以各种形式重用它。

以下是自定义输入组件的示例代码:

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

应用程序因按摩而崩溃:“例外:在控件上找不到指令注释”。

我在 Angular2 表单上搜索了各种教程,它们使用类似的方法,但输入元素位于表单内,给定输入的临时局部变量设置为 ngForm,如下所示:

ngControl="test"
#test = "ngForm"

我的问题是,是否可以在没有表单的输入组件中使用 ngControl?是的,那么如何修复异常?

我正在使用 Angular 2 - RC1 和 material2。

【问题讨论】:

    标签: angularjs angular angular2-forms


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2016-09-05
      • 2016-04-25
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多