【问题标题】:Error : No providers for Component错误:没有组件的提供者
【发布时间】:2017-06-14 10:05:25
【问题描述】:

我有一个指令,我在其中定义了一个单选按钮,我想调用一个组件的方法.. 当我在构造函数中注入组件时,出现此错误:ERROR Error: No provider for FoldersComponent!

directive.ts

   import { FoldersComponent } from '../folders/folders.component';
import { Directive, ElementRef, HostListener, Input, AfterViewInit, ViewChild, EventEmitter, Output } from '@angular/core';

declare var jQuery: any;

@Directive({
  selector: '[icheck]'
})

export class IcheckDirective implements AfterViewInit {

  @Output('icheck')
  callComponentFunction: EventEmitter<any> = new EventEmitter<any>();
  constructor(private el: ElementRef, private parentCmp: FoldersComponent) {
    jQuery(this.el.nativeElement).iCheck({
      checkboxClass: 'icheckbox_square-aero',
      radioClass: 'iradio_square-aero'
    }).on('ifChecked', function(event) {
      if (jQuery('input').attr('type') === 'radio') {
        this.parentCmp.selectType();
      }
    });
  }

  ngAfterViewInit(): void {
  }
}

文件夹.component.ts

@Component({
  selector: 'app-folders',
  templateUrl: './folders.component.html',
  styleUrls: ['./folders.component.css'],
})
export class FoldersComponent implements OnInit {
   constructor(
    private route: ActivatedRoute,
    private router: Router
  ) {  }

  selectType() {
    //    alert();
    console.log("Ici");
  }
}

文件夹.component.html

<input type="radio" icheck name="filters.type" [(ngModel)]="filters.type"                   value="IN"> (IN)

我的@NgModule

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    FoldersComponent,
  ],

【问题讨论】:

  • 太酷了...谢谢 ..;当我删除构造函数private parentCmp: FoldersComponent 的参数时,我不明白我的代码,它是有效的,但是当我添加它以使用组件的方法时,我得到了错误.. 非常有趣..
  • Thxxx 太辛苦了
  • @yurzui 你能解释一下你是怎么解决的吗?

标签: angular angular2-directives


【解决方案1】:

我遇到了同样的问题。原来我错过了在我的代码中更新以下内容:

  1. @Injectable({ providedIn: 'root' }) 在要导入的组件的 .ts 文件中。

  2. 在你的 appModule 的 NgModule 中添加组件。

【讨论】:

    【解决方案2】:

    您好像错过了注册FoldersComponent@NgModule({})

    你能把你的主文件贴在你用过NgModule的地方吗

    【讨论】:

      【解决方案3】:

      试试这个,你还没有导入你的组件。

      import {  FoldersComponent  } from '../path/to/component
      constructor(private _foldersComponent : FoldersComponent){}
      @Directive({
      selector: '[icheck]'
      
      })
       ... rest of file 
      

      然后从 FoldersComponent 调用方法只需使用 _foldersComponent。

      例如,this._foldersComponent.someMethod()

      【讨论】:

      • 如果您想拥有对组件的现有引用,则不应在提供程序数组中提供组件
      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 2017-11-24
      相关资源
      最近更新 更多