2017-03-16 35 views
2

我想在valor-softwareng2-select解決的問題後,安裝在我的node_modules(npm install --save ng2-select),我想注入SelectComponent如使用@ViewChild孩子,但我總是得到不確定的。它看起來真的很微不足道,我已經看到了該項目的github中的評論,它似乎爲許多人工作。 我在angular/CLI project如果我要添加更多的信息,請在評論中提及它。謝謝 。無法導入NG2選SelectComponent

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

態氮,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.d.ts

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

myComponent的:

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

    } 
+0

你應該實現'AfterViewInit'而不是'OnInit'。 (或兩者都有,但直到AfterViewInit後才能訪問它)。 [doc非常清楚](https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html)。 – n00dl3

+0

我應該在'AfterViewInit'方法中檢查'this.sysSearchInput'的值嗎? – mustafa918

+0

肯定,是的。 – n00dl3

回答

1

你應該訪問您的@ViewChildngAfterViewInit方法,它並沒有被設定時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 
+0

不幸的是,這不是錯誤,因爲即使在'ngAfterViewInit'和按鈕單擊後,檢查組件始終未定義的值 – mustafa918

+0

請看看我的其他評論和更新的答案。 – n00dl3

+0

啊好的,謝謝@ n00dl3我會嘗試 – mustafa918