自定义Angular 2指令不起作用

时间:2016-09-28 20:42:35

标签: angular angular2-directives

错误
模板解析错误:
无法绑定到' time-delta'因为它不是' p'。

的已知属性

文档中的解决方案
我必须将声明添加到声明数组中。我已经这样做了。

现在我的架构: 我有三个模块:

  • AppModule(root)
  • TimeModule(以后应该是一个带有一些指令的辅助模块)
  • AuthModule(登录,注册组件等)

AppModule:

@NgModule({
    imports: [
        TimeModule,
        BrowserModule,
        FormsModule,
        AuthModule,
        routing,
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        appRoutingProviders
    ],
    bootstrap: [AppComponent]
})

AuthModule:

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        authRouting
    ],
    declarations: [
        AuthComponent,
        LoginComponent,
        SignupComponent,
        LogoutComponent
    ],
    providers: [
        AuthGuard,
        AuthService
    ],
    bootstrap: [ LoginComponent ]
})

TimeModule:

@NgModule({
    declarations: [
        ReadableDatePipe,
        TimeDeltaDirective
    ]
})

现在我正在尝试在LoginComponent的视图中使用我的TimeDeltaDirective。 我已经尝试将指令添加到其他声明数组中,但这也不会起作用。

我感谢任何支持!感谢

TimeDeltaDirective:

import { Directive, ElementRef, Input, Renderer } from '@angular/core';

@Directive({ selector: '[time-delta]' })
export class TimeDeltaDirective {
    constructor(renderer: Renderer, el: ElementRef) {
        function getTimeDelta(date: Date) {
            var now = new Date();
            return (now.getTime() - date.getTime()) / 1000;
        }

        this.delta = getTimeDelta(new Date(this.date));
    }

    @Input('date') date: string;
    delta: number;
}

在LoginComponent中使用(示例):

@Component({
    selector: 'login',
    template: `
    <p date="2016-09-28 00:00:00" [time-delta]>{{delta}}</p>
  `
})

1 个答案:

答案 0 :(得分:6)

您需要从TimeDeltaDirective导出TimeModule,然后在TimeModule中导入AuthModule,因为您的LoginComponent已经在那里取消,这就是您想要的地方使用你的指令。这样,TimeDeltaDirective就可以在LoginComponent以及AuthModule的其他声明组件中使用@NgModule({ imports: [ BrowserModule, FormsModule, authRouting, TimeModule ], declarations: [ AuthComponent, LoginComponent, SignupComponent, LogoutComponent ], providers: [ AuthGuard, AuthService ], bootstrap: [ LoginComponent ] }) 。所以,它应该是这样的:

<强> AuthModule

@NgModule({
    declarations: [
        ReadableDatePipe,
        TimeDeltaDirective
    ],
    exports: [
        TimeDeltaDirective
    ]
})

<强> TimeModule

List liste = new ArrayList<>();
liste.stream().forEach(o->{
    //apply your math on o
});
相关问题