mustafa918
mustafa918

Reputation: 518

Can't import ng2-select SelectComponent

I'm trying to fix an issues in valor-software library ng2-select after install it in my node_modules ( npm install --save ng2-select ), I want to inject a SelectComponent as Child using @ViewChild but I get always undefined. its appear really trivial, I have seen comments in github of the project and it seems work for many people. I'm on angular/CLI project if I shoud add more information please mention it in comments. thanks .

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

gn2-select.d.ts content

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

content of select/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);

  }

Upvotes: 2

Views: 527

Answers (1)

n00dl3
n00dl3

Reputation: 21584

You should access your @ViewChild in the ngAfterViewInit method, it is not set yet when ngOnInit is called, see the 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
  }
}

You can also take a look at the Lifecycle Hooks

You should also use the class reference and not a string, as strings are for targeting ElementRef, not components:

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

Upvotes: 1

Related Questions