I'm trying to wrap my head around Angular 2 directives. In my code sample, I'm trying to mimic ngIf functionality. So I have a app.mycustomdirective.ts file:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[my-custom-if]'
})
export class MyCustomIfDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
@Input() set my-custom-if(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
I added it to my declarators:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyErrorDirective } from './app.myerrordirective';
import {MyCustomIfDirective} from './app.mycustomifdirective';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, MyErrorDirective, MyCustomIfDirective ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
And finally I add it to my component:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h2 *my-custom-if="condition">Hello {{name}}</h2>
<button (click)="condition = !condition">Click</button>`,
})
export class AppComponent {
name = 'Angular';
condition = false;
}
Now, when I try npm start
I get the following error:
src/app/app.mycustomifdirective.ts(13,17): error TS1005: '(' expected.
src/app/app.mycustomifdirective.ts(13,25): error TS1109: Expression expected.
src/app/app.mycustomifdirective.ts(13,37): error TS1005: ')' expected.
src/app/app.mycustomifdirective.ts(13,46): error TS1005: ';' expected.
src/app/app.mycustomifdirective.ts(20,1): error TS1128: Declaration or statement expected.
And I can't figure out what's happening. Does anyone have a clue?
The error come from this:
@Input() set my-custom-if(condition: boolean) { // error
^ ^ ^
You can try this one:
@Input() myCustomIf: boolean;
init () {
if (this.myCustomIf) {
// your code here
}
}
Then just call, this.init()
into your constructor
.
Follow this guide step by step.