动态 <select><option> 条件 <optgroup> 作为 ng-container 不工作

Dynamic <select><option> with conditional <optgroup> as ng-container not working

我创建了一个小的下拉组件,它将以下界面作为 <option>s:

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 在传递 choicesGroup 时是 true,但模板似乎总是在评估 !== 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;
}

为了完整起见——根据 Günter 接受的答案,这些是我的最终更改:

private grouped: boolean;

ngOnInit() {
    this.grouped = this.choices[0].constructor === Array;
}

并且在模板中,我将 ng-container 的条件更改为:

<ng-container *ngIf="grouped">...</ng-container>
<ng-container *ngIf="!grouped">...</ng-container>