加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

自定义Angular 2指令不起作用

发布时间:2020-12-17 17:27:03 所属栏目:安全 来源:网络整理
导读:错误 模板解析错误: 无法绑定到’time-delta’,因为它不是’p’的已知属性. 文档中的解决方案 我必须将声明添加到声明数组中.我已经这样做了. 现在我的架构: 我有三个模块: AppModule(root) TimeModule(以后应该是一个辅助模块,带有一些指令) AuthModule(
错误
模板解析错误:
无法绑定到’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
    ]
})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读