1

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

工作模块.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 { }

工作组件.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));
}

打字头.html

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

当我启动应用程序时,所有组件都可以正确呈现而没有任何错误,但我正在undefined接受console.log(this.options);

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

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

我采取的参考:

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

4

1 回答 1

2

你得到undefined是因为你试图打印optionsconstructor考虑它是@Input(),它还没有从父组件传递。在那里实现OnInit并打印它,你会看到它会起作用:

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

export class NgbdTypeaheadBasic implements OnInit {

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

}

您应该查看Angular 2 Lifecycle Hooks

于 2016-11-09T22:48:54.047 回答