Angular 4 指令错误 : Can't resolve all parameters for directive

标签 angular typescript angular-directive

我是 Angular 的新手,正在尝试注入(inject) basic structural directive来自 Angular 指南。这是我的指令:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[pcDropdown]'
})
export class DropdownDirective {
  private hasView = false;

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private items
  ) { }

  @Input() set pcDropdown(condition: boolean) {
    if (!condition && !this.hasView) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      this.hasView = true;
    } else if (condition && this.hasView) {
      this.viewContainer.clear();
      this.hasView = false;
    }
  }
}

我正在尝试将它注入(inject)我的 TradeModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
import { TradeComponent } from './trade.component';
import { DropdownDirective } from '../dropdown.directive/dropdown.directive';

@NgModule({
  imports: [
    CommonModule,
    SharedModule
  ],
  declarations: [TradeComponent, DropdownDirective],
  exports: [DropdownDirective]
})
export class TradeModule { }

并在我的 TradeComponent 模板中使用以下 HTML 部分:

...
<p *pcDropdown="true">
  TEST
</p>
...

但是我得到了错误:

Uncaught Error: Can't resolve all parameters for DropdownDirective: ([object Object], [object Object], ?).

Webstorm 也是我的 @Directive 装饰器的基础,并说如下:

Angular: Can't resolve all parameters for DropdownDirective in /home/commercialsuicide/Desktop/my-app/src/client/app/dropdown.directive/dropdown.directive.ts: ([object Object], [object Object], ?)

enter image description here

它还说我的 pcDropdown 输入未使用:

enter image description here

不得不说,我已经看到了this answer并且 emitDecoratorMetadata 已在 tsconfig.json 中设置为 true

请指出我拼写错误或忘记在我的代码中包含某些内容的地方。

非常感谢

最佳答案

private items 缺少类型参数。如果 Angular 无法将所有参数解析为提供者,则它无法创建组件实例。
解析为提供者仅适用于参数类型和 @Inject(...) 注释。

如果您不想注入(inject) items,请删除该参数。在任何情况下,您都不需要自己创建组件实例来显式传递参数。

关于Angular 4 指令错误 : Can't resolve all parameters for directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45194125/

相关文章:

javascript - 与 swiper 结合使用时奇怪的 ngx-translate 行为

html - 如何将点击事件分配给指令外的元素?

angular - 从附加到 <form> 的指令中访问 FormGroup 实例

angular - 如何使用 *ngFor 迭代对象键?

javascript - angular2 xhrfields withcredentials true

javascript - "rx"和 "rxjs"npm 包有什么区别?

typescript - 将联合类型转换为交集类型

javascript - ES6 相当于这个 Angular 2 typescript

javascript - 如何使用 Angular 和 webapi 或 mvc 处理测验应用程序中的安全性?

Angular react 形式 - 将 formArray 传递给子组件时出错