Reputation: 685
I'm trying to create a custom directive and I get this error:
The directive is included in declarations inside @NgModule. Nonetheless is not working. If you need more information on the error just ask. I don't know what's going on.
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 { }
Upvotes: 8
Views: 13621
Reputation: 29335
proper syntax is:
<input class="text" appInputFormat>
You put things in brackets when they're accepting an input, as in if you also declared an input of the same name on the directive, similarly you can use parens if you declare an output of the same name.
Upvotes: 4
Reputation: 60538
Looking at the documentation here: https://angular.io/guide/attribute-directives
This type of selector:
@Directive({
selector: '[appInputFormat]'
})
Builds an attribute directive.
It's the brackets ([]) that make it an attribute selector.
So it has to be used as an attribute like this:
<input class="text" appInputFormat>
Brackets when you define the selector, but no brackets in the Html when you use the directive.
Upvotes: 16