Angular 2 export class: 需要声明或声明

Angular 2 export class: Declaration or statement expected

我正在努力思考 Angular 2 个指令。在我的代码示例中,我试图模仿 ngIf 功能。所以我有一个 app.mycustomdirective.ts 文件:

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

我将它添加到我的声明符中:

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 { }

最后我将它添加到我的组件中:

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

现在,当我尝试 npm start 时,出现以下错误:

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.

而且我不知道发生了什么。有人知道吗?

错误来自于:

@Input() set my-custom-if(condition: boolean) { // error
               ^  ^  ^

你可以试试这个:

@Input() myCustomIf: boolean;
init () {
   if (this.myCustomIf) {
       // your code here
   }
}

然后只需拨打 this.init() 到您的 constructor

按照此 guide 一步步进行。