我在模板中使用 ng2-select 来选择项目,有一个名为“添加”的按钮,单击该按钮时应显示另一个选择字段,其中包含其他类别的项目列表。为此,我的代码的最简单版本如下所示:
@Component({
moduleId: module.id,
selector: 'client-user-detail',
templateUrl: `<div #one>
<ng-select #selectRole [allowClear]="true"
[multiple]="true" (data)="refreshValue($event)"
(selected)="onSelectRole($event)"
(removed)="removed($event)"
(typed)="typed($event)"
placeholder="Choose/Search">
</ng-select>
<button [disabled]="isDisable"
class="btn btn-default"
(click)="add()">
<i class=" fa fa-save"></i>
Add
</button>
`,
styleUrls: ['clientuserdetail.component.css']
})
export class TestComponent {
@ViewChild('selectRole') public select: SelectComponent;
@ViewChild('one') d1:ElementRef;
constructor(
private renderer: Renderer
) { }
add() {
let htmlText = `<ng-select #selectRole [allowClear]="true"
[multiple]="true" (data)="refreshValue($event)"
(selected)="onSelectRole($event)"
(removed)="removed($event)" (typed)="typed($event)"
placeholder="Choose/Search">
</ng-select>`;
this.renderer.invokeElementMethod
(this.d1.nativeElement,'insertAdjacentHTML',
['beforeend',htmlText]);
}
}
上面的代码不会创建选择字段。我在某处阅读了有关组件解析器在这种情况下很有用的内容,但我没有掌握使用它的明确方法。如果有人可以简单地向我解释如何解决这个问题,我将不胜感激。我需要清楚地说明如何在 angular 2 中动态添加或附加组件。在此先感谢您。
我无法准确回答您尝试添加字段的方式,我建议您将ng-select放在ngFor 中,这样您的add()函数将增加并删除所有viewChild。
import { Component } from '@angular/core';
/**
* Created by lejendarm on 08/08/17.
*/
class Role {
id: number;
label: string;
/* I'm not sure about the need of a constructor */
constructor() {
this.id = 0;
this.label = '';
}
}
@Component({
moduleId: module.id,
selector: 'client-user-detail',
template: `<div *ngFor="role in roles">
<ng-select [allowClear]="true"
[multiple]="true" (data)="refreshValue($event, role)"
(selected)="onSelectRole($event, role)"
(removed)="removed($event, role)"
(typed)="typed($event, role)"
placeholder="Choose/Search">
</ng-select>
</div>
<button [disabled]="isDisable"
class="btn btn-default"
(click)="add()">
<i class=" fa fa-save"></i>
Add
</button>`,
styleUrls: ['clientuserdetail.component.css']
})
export class TestComponent {
private roles: Array<Role>;
constructor(
) {
this.roles = [new Role()];
}
add() {
this.roles.push(new Role())
}
refreshValue($event, role) {}
onSelectRole($event, role) {}
removed($event, role) {}
typed($event, role) {}
}
PS:即使与您的问题没有直接联系,我也会使用模板而不是templateUrl并关闭 div #one 以显示更好的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句