自定义 Angular 2 指令无法正常工作。

12

错误
模板解析错误:
无法绑定到 'time-delta',因为它不是 'p' 的已知属性。

文档中的解决方案
我需要将指令添加到声明数组中。我已经完成了这个步骤。

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

  • AppModule(根)
  • TimeModule(稍后应该成为一些指令的辅助模块)
  • AuthModule(登录、注册组件等)

AppModule:

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

认证模块:

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

时间模块:

@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个回答

17
你需要从你的 TimeModule 中导出 TimeDeltaDirective 并将其导入到你的 AuthModule 中,因为你的 LoginComponent 是在那里声明的,这就是你想要使用指令的地方。这样,TimeDeltaDirective 将可供在 LoginComponent 以及 AuthModule 的其他声明组件中使用。所以应该像这样:

AuthModule

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

时间模块

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

谢谢你的回答。不幸的是这种方法没有起作用。我将TimeDeltaDirective添加到导出数组中,并将其添加到AuthModule的导入数组中。但仍然出现同样的错误。还有其他办法吗? - CodeWarrior
@UeliKramer 你是否已将 TimeDeltaDirectiveTimeModule 添加到 AuthModule 的导入中? - Stefan Svrkota
我已经将 TimeModule 添加到导入中。 - CodeWarrior
1
你有什么建议给我吗? - CodeWarrior
@UeliKramer 我找不到错误,如果您能在 plnkr 上重现它就太好了。这是一个快速入门,您可以编辑它以匹配您的代码: https://angular.io/resources/live-examples/quickstart/ts/plnkr.html - Stefan Svrkota
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接