在将 valor-software
库 ng2-select
安装到我的 node_modules ( npm install --save ng2- select
),我想使用 @ViewChild
将 SelectComponent
作为 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/