自定义Angular 2指令不起作用

前端之家收集整理的这篇文章主要介绍了自定义Angular 2指令不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
错误
模板解析错误
无法绑定到’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,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>
  `
})

解决方法

您需要从TimeModule导出TimeDeltaDirective,然后在AuthModule中导入TimeModule,因为您的LoginComponent已经在那里进行了decalred,那就是您要使用指令的地方.这样,TimeDeltaDirective将可用于LoginComponent以及AuthModule的其他声明组件.所以,它应该是这样的:

AuthModule

@NgModule({
    imports: [
        BrowserModule,authRouting,TimeModule
    ],bootstrap: [ LoginComponent ]
})

TimeModule

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

猜你在找的Angularjs相关文章