我在我的模板中使用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]);
}
}
以上代码不会创建选择字段。 我在某处读过有关组件的解析器在这种情况下可能有用,但我没有掌握使用它的明确方法。如果有人能够简单地向我解释如何解决这个问题,我将非常感激。我需要清楚地说明如何动态添加或附加角度2组件。提前谢谢。
答案 0 :(得分:1)
我无法完全按照您尝试添加字段的方式回答,我建议您将 ng-select 置于 ngFor 中您的添加()功能会增加并删除所有 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以显示更好的代码。< / p>