Javascript Angular 2导出类:需要声明或语句

Javascript Angular 2导出类:需要声明或语句,javascript,angular,angular2-directives,Javascript,Angular,Angular2 Directives,我正试着把我的头绕在棱角分明的方向上。在我的代码示例中,我试图模拟ngIf功能。所以我有一个app.mycustomdirective.ts文件: import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[my-custom-if]' }) export class MyCustomIfDirective { construct

我正试着把我的头绕在棱角分明的方向上。在我的代码示例中,我试图模拟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 { 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;  
}

我不知道发生了什么。有人有线索吗?

错误来自以下方面:

@Input() set my-custom-if(condition: boolean) { // error
               ^  ^  ^
你可以试试这个:

@Input() myCustomIf: boolean;
init () {
   if (this.myCustomIf) {
       // your code here
   }
}
然后将this.init调用到构造函数中


按此步骤进行操作。

函数名中不能有“-”
@Input() set my-custom-if(condition: boolean) { // error
               ^  ^  ^
@Input() myCustomIf: boolean;
init () {
   if (this.myCustomIf) {
       // your code here
   }
}