ng2-组件属性绑定不起作用

时间:2016-11-09 22:32:29

标签: twitter-bootstrap angular ng-bootstrap

我正在开发一个Angular 2应用程序,我在其中创建了一个名为JobComponent的组件,其中包含一个名为candidate_types的属性,并尝试使用属性绑定将该属性绑定到NgbdTypeaheadBasic组件,但是它不起作用,我不知道为什么,下面是文件。

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" />

当我启动应用时,所有组件都正常呈现,没有任何错误,但我undefined

获得了console.log(this.options);

我正在尝试实现Angular 2 Bootstrap Typehead Component:

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

我参考过:

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

1 个答案:

答案 0 :(得分:2)

您收到undefined,因为您尝试在options中打印constructor并认为它是@Input(),但此时尚未从父组件传递。OnInit实施import { OnInit } from '@angular/core'; export class NgbdTypeaheadBasic implements OnInit { ngOnInit() { console.log(this.options); } } 并在那里打印,你会发现它会起作用:

Jsoup.connect("http://uselectionatlas.org/RESULTS/national.php?f=1&year=2008&off=0&elect=0")
.userAgent("Mozilla/5.0")
.timeout(0).get();

您应该查看Angular 2 Lifecycle Hooks