如何制作<mat-list-option>
–在组件sub
中声明–“订阅”组件<mat-selection-list>
外部的sub
(例如,组件{{1 }})?
(不幸的是,我无法设法使Stackblitz与我公司的代理一起工作,所以我仅将示例中的相关内容放进去)
示例1 (有效,没有组件app
)
(app.component.html)
sub
(app.component.ts)
<div>{{selections | json}}</div>
<mat-selection-list [(ngModel)]="selections">
<mat-list-option [value]="{x: 1}">x: 1</mat-list-option>
<mat-list-option [value]="{x: 2}">x: 2</mat-list-option>
<mat-list-option [value]="{y: 1}">y: 1</mat-list-option>
<mat-list-option [value]="{y: 2}">y: 2</mat-list-option>
</mat-selection-list>
此示例按预期方式工作。呈现所有4个选项,它们的选择反映在@Component({
templateUrl: './app.component.html',
})
export class AppComponent {
selections = [];
}
属性中(所有选项的值都是javascript对象,并且已正确插入selections
数组中/从中删除)。
示例2 (不起作用,在selections
和sub
之间添加了组件<mat-selection-list>
)
(app.component.html)
<mat-list-option>
(sub.component.html)
<div>{{selections | json}}</div>
<mat-selection-list [(ngModel)]="selections">
<sub></sub>
</mat-selection-list>
(app.component.ts不变; sub.component.ts很小)
此示例确实呈现了所有选项。他们的选择不会反映回 <mat-list-option [value]="{x: 1}">x: 1</mat-list-option>
<mat-list-option [value]="{x: 2}">x: 2</mat-list-option>
<mat-list-option [value]="{y: 1}">y: 1</mat-list-option>
<mat-list-option [value]="{y: 2}">y: 2</mat-list-option>
属性(也正如预期的那样,因为在实例化每个selections
时,没有可见的<mat-list-option>
可供他们订阅)。
示例3 (尝试转发<mat-selection-list>
,但无济于事)
(app.component.ts)
<mat-selection-list>
我希望这个可以工作。但是我只能得到一个错误:
@Component({
...
viewProviders: [{ provide: MatSelectionList, useExisting: MatSelectionList }]
})
export class AppComponent {
selections = [];
}
如何进行这项工作?
注意
我想观察一下,Cannot instantiate cyclic dependency! MatSelectionList (...)
指令(与ngModel
和/或ngForm
协同工作)只需添加适当的{{1} }到实例化的ngModelGroup
或viewProviders
(包括)与实例化的ngForm
(不包括)之间的所有中间组件。
尽管它们的注入途径不同:ngModelGroup
通过 [{{3]拥有其父级ngModel
(包括ngModel
和ControlContainer
)。 }}] :
ngForm
ngModelGroup
通过 [source] 这样做:
constructor(@Optional() @Host() parent: ControlContainer, ...) {...}
我不了解这些差异及其含义。
答案 0 :(得分:1)
MatSelectList的内置SelectionModel在示例2方法中可以正常工作。问题是NgModel(这可能是错误或固有限制)。您可以通过侦听列表的选择更改并直接管理模型来解决此问题。例如:
HTML
<mat-selection-list [ngModel]="selections" (selectionChange)="handleSelectionChange($event.option)">
<sub></sub>
</mat-selection-list>
TS
selections = [];
handleSelectionChange(option: MatSelectionListChange) {
if (option.selected) {
this.selections.push(option.value);
}
else {
const index = this.selections.indexOf(option.value);
this.selections.splice(index, 1);
}
}