javascript - Angular 2 导出类 : Declaration or statement expected

标签 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.

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

最佳答案

错误来自于此:

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

你可以试试这个:

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

然后只需调用 this.init() 到您的构造函数中即可。

关注此guide一步一步来。

关于javascript - Angular 2 导出类 : Declaration or statement expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49479297/

相关文章:

angular2-template - ngx bootstrap popoverTitle 呈现为 HTML

angular - 如何强制重新加载/刷新组件 View ?

javascript - 无法计算出 jQuery find 来定位层次结构中的对象

JavaScript 错误 : invalid label? 这是什么意思?

angular - 如何找到哪些组件存在冲突?

javascript - Ignite UI TreeList 绑定(bind)两个名称和值

javascript - 将动态属性添加到对象末尾

javascript - 如何管理网站中的 jQuery 库?

使用 HttpClient 模块的 Angular 4 设置 header

angular - *ngIf 不对 bool 值变化使用react