gpt4 book ai didi

Angular - 数组作为选择选项值

转载 作者:行者123 更新时间:2023-12-04 10:57:58 26 4
gpt4 key购买 nike

我有这个 typescript :

public sendAlertDays: Array<any> = [
{ value: [0, 1, 2, 3, 4, 5, 6], text: "all days" },
{ value: [0, 1, 2, 3, 4], text: "monday-friday" },
{ value: [5, 6], text: "saturday-sunday" },
{ value: [0], text: "monday" },
{ value: [1], text: "tuesday" },
{ value: [2], text: "wednesday" },
{ value: [3], text: "thursday" },
{ value: [4], text: "friday" },
{ value: [5], text: "saturday" },
{ value: [6], text: "sunday" }
];

sendAlertDay: number[] = [0];

我的 Angular 模板没有预先选择“星期一”但我已经初始化好了 sendAlertDay: number[] = [0]
<mat-select [(value)]="sendAlertDay" class="mat-primary">
<mat-option *ngFor="let day of sendAlertDays" [value]="day.value">
{{day.text}}
</mat-option>
</mat-select>

最佳答案

您将需要使用 compareWith mat-select 的属性(property).

@Input() compareWith: (o1: any, o2: any) => boolean

Function to compare the option values with the selected values. The first argument is a value from an option. The second is a value from the selection. A boolean should be returned.



您的组件:

public sendAlertDays: Array<any> = [
{ value: [0, 1, 2, 3, 4, 5, 6], text: "all days" },
{ value: [0, 1, 2, 3, 4], text: "monday-friday" },
{ value: [5, 6], text: "saturday-sunday" },
{ value: [0], text: "monday" },
{ value: [1], text: "tuesday" },
{ value: [2], text: "wednesday" },
{ value: [3], text: "thursday" },
{ value: [4], text: "friday" },
{ value: [5], text: "saturday" },
{ value: [6], text: "sunday" }
];

sendAlertDay: number[] = [0];

compareFN(optionValue: number[], selectionValue: number[]) {
// compare two arrays
return (
optionValue.length === selectionValue.length &&
optionValue.every((value, index) => value === selectionValue[index])
);
}

您的模板:

 <mat-select [(value)]="sendAlertDay" [compareWith]="compareFN" class="mat-primary">
<mat-option *ngFor="let day of sendAlertDays" [value]="day.value">
{{day.text}}
</mat-option>
</mat-select>

Demo在堆栈 Blitz 中

关于Angular - 数组作为选择选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59053196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com