angular 2无法动态创建selectpicker(bootstrap)

时间:2016-07-12 19:31:05

标签: angular angular-ui-bootstrap angular2-forms

我正在尝试动态地创建教育形式。也就是说,当用户点击按钮"添加教育"时,它将创建一种教育形式,供用户填写信息。我使用bootstrap中的selectpicker为用户选择年份和月份。但是,angular2在加载教育表单时无法创建selectpicker。如果我静态创建selectpicker,它将起作用,但不是动态的。真想知道问题所在。以下是相关文件中代码的一部分:

应用-page.html中

<div class="row education">
    <div class="col-md-1 col-xs-12 page-label">
        Education
    </div>
    <div class="col-md-10 col-xs-12 page-label-link">
        <ul class="ul-no-margin">
          <li *ngFor="let education of educations; let i = index">
            <education-form [index]="i" [education]="education" (deleteEvent)="deleteEducation($event)"></education-form>
          </li>
        </ul>
        <a (click)="addEducation()">Add education</a>
    </div>
</div>

education.html

<select class="inline-box selectpicker" data-style="btn-secondary" data-width="auto" tabindex="-1" id="" required="">
    <option value="0">Month *</option>
    <option value="1">Jan</option>
    <option value="2">Feb</option>
    <option value="3">Mar</option>
    <option value="4">Apr</option>
    <option value="5">May</option>                
    <option value="6">Jun</option>
    <option value="7">Jul</option>
    <option value="8">Aug</option>
    <option value="9">Sep</option>
    <option value="10">Oct</option>
    <option value="11">Nov</option>
    <option value="12">Dec</option>
</select>

新的教育在申请页面中显示:

<li *ngFor="let education of educations; let i = index"
    <education-form [index]="i" [education]="education" (deleteEvent)="deleteEducation($event)"></education-form>
</li>

如果我删除&#34; selectpicker&#34;在class属性中,select标签工作正常,但它无法从bootstrap显示漂亮的布局。如果我添加&#34; selectpicker&#34;在class属性中,select标签不起作用。它不会在屏幕上显示任何内容。

希望有人能帮我解决问题。谢谢。

1 个答案:

答案 0 :(得分:2)

我发现我没有在我的education.ts文件中包含jQuery模块。以下是正确的代码。

education.ts:

import {Component, ViewEncapsulation, Input, Output, EventEmitter} from '@angular/core';
import {ROUTER_DIRECTIVES} from '@angular/router-deprecated';
// import education class
import {Education} from '../model/education';

declare var jQuery: any;

@Component({
  selector: 'education-form',
  template: require('./education-form.html'),
  host: {
    class: 'education-form'
  },
  encapsulation: ViewEncapsulation.None,
})
export class EducationForm{
    // the vars to store data from parent page
    @Input() index: number;
    @Input() education: Education;

    // the var to invoke an event of parent page
    @Output() deleteEvent = new EventEmitter<number>();


    ngOnInit(): void {
        jQuery('.selectpicker').selectpicker();
    }

    // the function to delete form of education
    deleteEducation(){
        this.deleteEvent.emit(this.index);
    }

}

我添加了

declare var jQuery: any;

ngOnInit(): void {
        jQuery('.selectpicker').selectpicker();
    }

然后它的工作原理。请记住在AngularJS中包含模块。