【问题标题】:Can't import ng2-select SelectComponent无法导入 ng2-select SelectComponent
【发布时间】:2017-08-07 10:47:24
【问题描述】:

我正在尝试修复valor-softwareng2-select 中的问题,在将其安装到我的node_modules (npm install --save ng2-select) 后,我想使用@ViewChildSelectComponent 作为子级注入,但我总是不确定. 它看起来真的很微不足道,我在项目的 github 中看到了 cmets,它似乎对很多人有用。 我在angular/CLI project,如果我需要添加更多信息,请在 cmets 中提及。谢谢 。

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);

  }

【问题讨论】:

  • 你应该实现AfterViewInit而不是OnInit。 (或两者兼有,但在 AfterViewInit 之前您将无法访问它)。 doc is very clear about that.
  • 我应该在“AfterViewInit”方法中检查“this.sysSearchInput”的值吗?
  • 当然,是的。
  • 不幸的是,这不是错误,因为即使在 'ngAfterViewInit' 和按钮单击之后检查过该组件始终未定义值
  • "SelectComponent" 不是有效的选择器,SelectComponent 是。

标签: javascript angular select


【解决方案1】:

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

在调用 ngAfterViewInit 回调之前设置视图查询。

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

【讨论】:

  • 不幸的是,这不是错误,因为即使在ngAfterViewInit 和按钮单击之后检查过组件始终是未定义值
  • 啊好的谢谢@n00dl3 我会试试的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多