Angular 7:无法绑定到“指令”,因为它不是“元素”的已知属性

时间:2019-01-22 23:59:57

标签: angular angularjs-directive

我正在尝试创建自定义指令,但出现此错误:

enter image description here

该指令包含在@NgModule内部的声明中。尽管如此,仍无法正常工作。如果您需要有关错误的更多信息,请询问。我不知道发生了什么。

app.component.html

<input class="text" [appInputFormat]>

input-format.directive.ts

[![import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[appInputFormat]'
})
export class InputFormatDirective {

    constructor(){};

  @HostListener('focus')  onFocus(){
    console.log('on Focus');
  }
  @HostListener('blur')  onBlur(){
    console.log('on Blur');
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule} from '@angular/forms';



import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CourseComponent } from './course/course.component';
import { FavoriteComponent } from './favorite/favorite.component';
import { PanelComponent } from './panel/panel.component';
import { LikeButtonComponent } from './like-button/like-button.component';
import { LikeCountComponent } from './like-count/like-count.component';
import { DirectivesComponent } from './directives/directives.component';
import { HiddenComponent } from './hidden/hidden.component';
import { SwitchcaseComponent } from './switchcase/switchcase.component';
import { ForComponent } from './for/for.component';
import { TrackbyComponent } from './trackby/trackby.component';
import { IfComponent } from './if/if.component';
import { StyleComponent } from './style/style.component';
import { TransopComponent } from './transop/transop.component';
import { InputFormatDirective } from './input-format.directive';

@NgModule({
  declarations: [
    AppComponent,
    CourseComponent,
    FavoriteComponent,
    PanelComponent,
    LikeButtonComponent,
    LikeCountComponent,
    DirectivesComponent,
    HiddenComponent,
    SwitchcaseComponent,
    ForComponent,
    TrackbyComponent,
    IfComponent,
    StyleComponent,
    TransopComponent, 
    InputFormatDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

2 个答案:

答案 0 :(得分:5)

在此处查看文档:{​​{3}}

这种选择器:

@Directive({
  selector: '[appInputFormat]'
})

构建属性指令。

  

使方括号([])成为属性选择器。

因此必须将其用作这样的属性:

<input class="text" appInputFormat>

定义选择器时使用方括号,但使用指令时HTML中没有方括号。

答案 1 :(得分:2)

正确的语法是:

<input class="text" appInputFormat>

当它们接受输入时,可以将它们放在方括号中,就像在指令上也声明了相同名称的输入一样,如果声明相同名称的输出,则可以使用parens。