如何在Angular2中将预先存在的标签添加到Select2

时间:2016-08-09 12:26:42

标签: javascript angularjs angular typescript

HTML:

<select data-placeholder="Skill List" style="width:100%;" class="chzn-select form-control" multiple="multiple">
    <option *ngFor="#skill of allSkills" [ngValue]="skill">{{skill}}
    </option>
</select>

TS:

allSkills = ['Welding', 'Forklifting'];
selectedSkill = ['Welding'];

ngOnInit(): void {
    jQuery('.chzn-select').select2();
}

如何最初添加 selectedSkill

1 个答案:

答案 0 :(得分:1)

只需将ngModel绑定添加到select标记:

<select data-placeholder="Skill List" 
        [(ngModel)]="selectedSkill" 
        style="width:100%;" 
        class="chzn-select form-control" 
        multiple="multiple">

    <option *ngFor="#skill of allSkills" [ngValue]="skill">
        {{skill}}
    </option>

</select>

在您的代码中:

allSkills = ['Welding', 'Forklifting'];
selectedSkill = allSkills[0]; // or just 'Welding'

ngOnInit(): void {
    jQuery('.chzn-select').select2();
}