javascript - 无法导入 ng2-select SelectComponent

标签 javascript angular select

在将 valor-softwareng2-select 安装到我的 node_modules ( npm install --save ng2- select ),我想使用 @ViewChildSelectComponent 作为 Child 注入(inject),但我总是未定义。 它看起来真的很微不足道,我在该项目的 github 中看到了评论,它似乎对很多人都有效。 我在 angular/CLI 项目中,如果我想添加更多信息,请在评论中提及。谢谢 。

node_modules
    |
    + --ng2-select
        |
        +--ng2-select.d.ts
        |
        +--select/
            |
            +--select.d.ts
            |
            +-- ...

gn2-select.d.ts内容

export * from './select/common';
export * from './select/off-click';
export * from './select/select.module';
export * from './select/select';
export * from './select/select-interfaces';
export * from './select/select-item';
export * from './select/select-pipes';

select/select.d.ts 的内容

export declare class SelectComponent implements OnInit, ControlValueAccessor        {
     private sanitizer;
     .....
}

我的组件:

import { Component, OnInit, ViewChild } from '@angular/core';
import { SelectComponent }  from 'ng2-select';

export class SubSystemComponent implements OnInit {
 @ViewChild('SelectComponent') 
private sysSearchInput: SelectComponent;

  constructor(private sysService : SubSysService) { }

  ngOnInit() {
    console.log(this.sysSearchInput);

  }

最佳答案

您应该在 ngAfterViewInit 方法中访问您的 @ViewChild,它在调用 ngOnInit 时尚未设置,请参阅 docs :

View queries are set before the ngAfterViewInit callback is called.

import {AfterViewInit, Component, Directive, ViewChild} from '@angular/core';
@Directive({selector: 'child-directive'})
class ChildDirective {
}
@Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
class SomeCmp implements AfterViewInit {
  @ViewChild(ChildDirective) child: ChildDirective;
  ngAfterViewInit() {
    // child is set
  }
}

您还可以查看 Lifecycle Hooks

您还应该使用类引用而不是字符串,因为字符串用于定位 ElementRef,而不是组件:

@ViewChild('SelectComponent') // invalid
@ViewChild(SelectComponent) // valid

关于javascript - 无法导入 ng2-select SelectComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42831066/

相关文章:

MySQL - 选择所有不包含特定值的唯一记录

javascript - 如何制作一个包含 ng-repeat 中使用的 div 的指令?

javascript - 如何从 mozilla 附加组件使用页面的 jQuery 方法?

javascript - 计算滑动平均值

javascript - 如何在 typescript 中访问geoJson坐标数组?

mysql - 在 SELECT 中重命名列多个 id

javascript - 使用 HTML 5 Canvas 旋转 Base64 图像数据 : final transformation is cropped and wrongly translated

javascript - 图像上传功能在 Angular 6 中不起作用

angular - FormControl 显示值

select - 设置默认值 ACF 选择