我创建了一个小的下拉组件,它采用以下界面作为 <option>
小号:
interface DropdownSelectChoice {
label: string;
key: string;
}
接受一维或二维选择数组的组件
@Input() choices: DropdownSelectChoice[] | DropdownSelectChoice[][];
如果传递了一个二维数组选择,创建未标记的<optgroup>
每组选择的 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>
如果我向它传递一个一维数组,它会按预期工作:
choices: DropdownSelectChoice[] = [
{
label: "One",
key: "1"
},
{
label: "Two",
key: "2"
}
];
如果我给它传递一个二维数组:
choicesGroup: DropdownSelectChoice[][] = [
[
{
label: "One",
key: "1"
},
{
label: "Two",
key: "2"
}
],
[
{
label: "Three",
key: "3"
},
{
label: "Four",
key: "4"
}
]
];
我得到 choicesGroup.length
空白 <option>
没有 <optgroup>
.
在下拉组件的初始化程序中设置断点,我确认 this.choices[0].constructor === Array
是true
通过时 choicesGroup
, 但模板似乎总是在评估 !== Array
模板路径。
我忽略了什么我没有注意到的愚蠢的事情?
最佳答案
类型不能在模板中以这种方式使用。
尝试
<ng-container *ngIf="choices[0].isArray">
<ng-container *ngIf="!choices[0].isArray">
如果您仍然想使用constructor === Array
,您需要创建一个方法并在那里进行比较。
<ng-container *ngIf="isArray(choices[0])">
isArray(obj) {
return obj.constructor === Array;
}
关于angular - 具有条件 <optgroup> 的动态 <select><option> 作为 ng-container 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43615773/