Angular 动态<;选择>&书信电报;选项>;有条件<;optgroup>;因为ng容器不工作
我创建了一个小的下拉组件,它将以下界面作为Angular 动态<;选择>&书信电报;选项>;有条件<;optgroup>;因为ng容器不工作,angular,html-select,angular-template,Angular,Html Select,Angular Template,我创建了一个小的下拉组件,它将以下界面作为s: interface DropdownSelectChoice { label: string; key: string; } 要接受一维或二维选择数组的组件 @Input() choices: DropdownSelectChoice[] | DropdownSelectChoice[][]; 如果传递了一个二维选择数组,则要为每组选择创建未标记的s: <span [class.disabled]="disabled"&g
s:
interface DropdownSelectChoice {
label: string;
key: string;
}
要接受一维或二维选择数组的组件
@Input() choices: DropdownSelectChoice[] | DropdownSelectChoice[][];
如果传递了一个二维选择数组,则要为每组选择创建未标记的
s:
<span [class.disabled]="disabled">
<select (ngModelChange)="choose($event)"
[disabled]="disabled"
[(ngModel)]="defaultChoice">
<ng-container *ngIf="choices[0].constructor === Array">
<optgroup *ngFor="let group of choices" [label]="null">
<option *ngFor="let choice of group"
[value]="choice.key">
{{ choice.label }}
</option>
</optgroup>
</ng-container>
<ng-container *ngIf="choices[0].constructor !== Array">
<option *ngFor="let choice of choices"
[value]="choice.key">
{{ choice.label }}
</option>
</ng-container>
</select>
</span>
如果我传递一个二维数组:
choicesGroup: DropdownSelectChoice[][] = [
[
{
label: "One",
key: "1"
},
{
label: "Two",
key: "2"
}
],
[
{
label: "Three",
key: "3"
},
{
label: "Four",
key: "4"
}
]
];
我得到choicesGroup.length
blank
s,没有
在下拉组件的初始化器中设置断点,我确认传递choicesGroup
时this.choices[0]。构造函数===Array
为true
,但模板似乎总是在计算!==数组
模板路径
我忽略了什么愚蠢的事情而没有注意到?类型不能以这种方式在模板中使用 试一试
为了完整性——根据甘特接受的答案,以下是我最后的修改:
private grouped: boolean;
ngOnInit() {
this.grouped = this.choices[0].constructor === Array;
}
在模板中,我将ng容器的条件更改为:
<ng-container *ngIf="grouped">...</ng-container>
<ng-container *ngIf="!grouped">...</ng-container>
。。。
...
我就知道你会有答案的!我猜我试图访问模板中不允许的内容。我在选项[0]中得到了相同的(不正确的)行为。iArray
在模板中,因此我将原始签入ngOnInit
,并将该状态存储到另一个类成员布尔值中,以简化模板。
<ng-container *ngIf="!choices[0].isArray">
<ng-container *ngIf="isArray(choices[0])">
isArray(obj) {
return obj.constructor === Array;
}
private grouped: boolean;
ngOnInit() {
this.grouped = this.choices[0].constructor === Array;
}
<ng-container *ngIf="grouped">...</ng-container>
<ng-container *ngIf="!grouped">...</ng-container>