mat-selection-list 不适用于 *ngFor
mat-selection-list not working with *ngFor
我正在尝试使用垫子选择列表作为垫子菜单中的一个选项:
export class AppComponent implements OnInit() {
items: string[] = ['item1', 'item2', 'item3']
constructor(){}
}
<button [matMenuTriggerFor]="settings">
<\button>
<mat-menu #settings="matMenu">
<button mat-menu-item [matMenuTriggerFor]="items">Items<\button>
<\mat-menu>
<mat-menu #items="matMenu">
<mat-selection-list>
<mat-list-option *ngFor="let item of items" [value]="item">
{{item}}
<\mat-list-option>
<\mat-selection-list>
<\mat-menu>
当我点击按钮时,会出现一个菜单,其中可以选择元素“Items”。在“项目”中,我希望看到项目 item1
、item2
和 item3
的列表。但是,没有显示任何内容并抛出以下错误:
Error: Cannot find a differ supporting object [object Object] of type 'object'. NgFor only supports binding to Iterables such as Arrays.
为什么我的数组 items
不适合 ngFor?我错过了什么?如果我手动添加每个 mat-list-option,列表会正确填充,但使用 ngFor 会给我带来问题。
我看到两个可能的问题:
1。您对 #settings="matMenu"
和 #items="matMenu"
的使用将 settings
和 items
的值设置为 matMenu
的相同引用,这可能不是您想要的。来自文档:
How Angular assigns values to template variables
...
If the variable specifies a name on the right-hand side, such as #var="ngModel"
, the variable refers to the directive or component on the element with a matching exportAs name.
您应该只使用 #settings
和 #items
。然而...
2。模板中的 #items
将覆盖组件中的 items: string[]
。为您的 <mat-menu>
元素选择一个不同的变量名称——例如 #itemsMenu
。
我正在尝试使用垫子选择列表作为垫子菜单中的一个选项:
export class AppComponent implements OnInit() {
items: string[] = ['item1', 'item2', 'item3']
constructor(){}
}
<button [matMenuTriggerFor]="settings">
<\button>
<mat-menu #settings="matMenu">
<button mat-menu-item [matMenuTriggerFor]="items">Items<\button>
<\mat-menu>
<mat-menu #items="matMenu">
<mat-selection-list>
<mat-list-option *ngFor="let item of items" [value]="item">
{{item}}
<\mat-list-option>
<\mat-selection-list>
<\mat-menu>
当我点击按钮时,会出现一个菜单,其中可以选择元素“Items”。在“项目”中,我希望看到项目 item1
、item2
和 item3
的列表。但是,没有显示任何内容并抛出以下错误:
Error: Cannot find a differ supporting object [object Object] of type 'object'. NgFor only supports binding to Iterables such as Arrays.
为什么我的数组 items
不适合 ngFor?我错过了什么?如果我手动添加每个 mat-list-option,列表会正确填充,但使用 ngFor 会给我带来问题。
我看到两个可能的问题:
1。您对 #settings="matMenu"
和 #items="matMenu"
的使用将 settings
和 items
的值设置为 matMenu
的相同引用,这可能不是您想要的。来自文档:
How Angular assigns values to template variables
...
If the variable specifies a name on the right-hand side, such as#var="ngModel"
, the variable refers to the directive or component on the element with a matching exportAs name.
您应该只使用 #settings
和 #items
。然而...
2。模板中的 #items
将覆盖组件中的 items: string[]
。为您的 <mat-menu>
元素选择一个不同的变量名称——例如 #itemsMenu
。