Akshay Khale
Akshay Khale

Reputation: 8361

ng2- component property binding not working

I am working on an Angular 2 app in which I have created a component named JobComponentwith a property named candidate_types and trying to bind the property using attribute binding to NgbdTypeaheadBasic component, but it's not working, I don't know why, below are the files.

job.module.ts

import { NgbdTypeaheadBasic } from './typehead.component';
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { JobComponent }   from './job.component';
@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ JobComponent, NgbdTypeaheadBasic],
  bootstrap:    [ JobComponent ]
})


export class JobModule { }

job.component.ts

import { Component } from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Component({
    selector : 'job_block',
    template : "<ngbd-typeahead-basic [options]='candidate_types'></ngbd-typeahead-basic>",
})

export class JobComponent {
    candidate_types:any=['air', 'ocean'];
}

typehead.component.ts

import {Component,Input} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

@Component({
  selector: 'ngbd-typeahead-basic',
  templateUrl: './partials/third-party/typehead.html'
})
export class NgbdTypeaheadBasic {
  public model: any;

  states:any;

  @Input() options:any;

  constructor() { console.log(this.options); }

  search = (text$: Observable<string>) =>
    text$
      .debounceTime(200)
      .distinctUntilChanged()
      .map(term => term.length < 2 ? []
        : this.states.filter(v => new RegExp(term, 'gi').test(v)).splice(0, 10));
}

typehead.html

<input type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search" />

When I launched the app all the components are getting rendered properly without any error, but I am getting undefined for console.log(this.options);

I am trying to implement Angular 2 Bootstrap Typehead Component:

https://ng-bootstrap.github.io/#/components/typeahead

Reference that I have taken:

https://angular.io/docs/ts/latest/tutorial/toh-pt3.html

Upvotes: 1

Views: 220

Answers (1)

Stefan Svrkota
Stefan Svrkota

Reputation: 50623

You are getting undefined because you are trying to print options in constructor and considering it is @Input(), it is not yet passed from parent component at that moment. Implement OnInit and print it there, you'll see it will work:

import { OnInit } from '@angular/core';

export class NgbdTypeaheadBasic implements OnInit {

ngOnInit() {
console.log(this.options);
}

}

You should check out Angular 2 Lifecycle Hooks.

Upvotes: 2

Related Questions