![](/img/trans.png)
[英]How to use mat-list-option in mat-selection-list indirectly in angular material?
[英]Angular material <mat-selection-list> and <mat-list-option> across template boundaries
如何使<mat-list-option>
-在component sub
声明-“订阅”到component sub
外部的<mat-selection-list>
(例如,component app
)?
(不幸的是,我无法使Stackblitz与我公司的代理一起工作,因此我仅将示例中的相关内容放进去)
示例1 (正常工作,没有组件sub
)
(app.component.html)
<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>
(app.component.ts)
@Component({
templateUrl: './app.component.html',
})
export class AppComponent {
selections = [];
}
本示例按预期方式工作。 呈现所有4个选项,它们的选择反映在selections
属性中(所有选项的值都是javascript对象,并且已正确插入到selections
数组中/从中删除)。
示例2 (不起作用,在<mat-selection-list>
和<mat-list-option>
之间添加了component sub
)
(app.component.html)
<div>{{selections | json}}</div>
<mat-selection-list [(ngModel)]="selections">
<sub></sub>
</mat-selection-list>
(sub.component.html)
<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>
(app.component.ts不变; sub.component.ts无关紧要)
本示例确实呈现了所有选项。 它们的选择不会反映到selections
属性(也正如预期的那样,因为在每个实例化每个<mat-list-option>
的点上,它们都没有可见的<mat-selection-list>
可供订阅)。
示例3 (尝试转发<mat-selection-list>
毫无用处)
(app.component.ts)
@Component({
...
viewProviders: [{ provide: MatSelectionList, useExisting: MatSelectionList }]
})
export class AppComponent {
selections = [];
}
我希望这个可以工作。 但是我只能得到一个错误:
Cannot instantiate cyclic dependency! MatSelectionList (...)
如何使这项工作?
注意
我想观察到ngModel
指令(与ngForm
和/或ngModelGroup
)仅通过在一个实例化ngForm
或ngModelGroup
(包括)和一个实例化之间的所有中间组件中添加适当的viewProviders
,就可以跨模板边界完美地工作。 ngModel
(不包含)。
不过,它们的注入途径并不相同: ngModel
通过[ source ] ngModel
获取其父ControlContainer
(包含ngForm
和ngModelGroup
):
constructor(@Optional() @Host() parent: ControlContainer, ...) {...}
而<mat-list-option>
通过[ source ]这样做:
constructor(..., @Inject(forwardRef(() => MatSelectionList)) public selectionList: MatSelectionList) {...}
我不了解各种差异及其含义。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.