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

Iva*_*ich 4 angularjs-directive angular

我试图创建一个自定义指令,但出现此错误:

在此处输入图片说明

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

app.component.html

<input class="text" [appInputFormat]>
Run Code Online (Sandbox Code Playgroud)

输入格式指令

[![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');
  }
}
Run Code Online (Sandbox Code Playgroud)

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 { }
Run Code Online (Sandbox Code Playgroud)

Deb*_*ahK 5

在此处查看文档:https : //angular.io/guide/attribute-directives

这种选择器:

@Directive({
  selector: '[appInputFormat]'
})
Run Code Online (Sandbox Code Playgroud)

构建属性指令。

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

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

<input class="text" appInputFormat>
Run Code Online (Sandbox Code Playgroud)

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

  • 如果指令还声明了同名的输入,则确实可以在选择器中使用方括号 (2认同)