Angular 2出口类:预期的声明或声明

时间:2018-03-25 18:21:45

标签: javascript angular angular2-directives

我试图绕过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.

我无法弄清楚发生了什么。有没有人有线索?

1 个答案:

答案 0 :(得分:1)

错误来自:

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

你可以尝试这个:

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

然后,只需致电this.init()进入constructor

一步一步地遵循guide