angular - 是否可以使用 ng-content 将 mat-options 传递给我的自定义 mat-select 组件?
问题描述
我有一个自定义选择组件,想用ng-content
它来传递我的选项,如下所示:
<lib-select [(selected)]="selected" (selectedChange)="onChange($event)">
<mat-option [value]="0">Value 1</mat-option>
<mat-option [value]="1">Value 2</mat-option>
<mat-option [value]="2">Value 3</mat-option>
<mat-option [value]="3">Value 4</mat-option>
<mat-option [value]="4">Value 5</mat-option>
</lib-select>
这似乎不起作用。一开始它甚至没有显示选项。我找到了一个让它们显示的技巧,但我仍然无法选择任何东西。这是我的组件:
<mat-select panelClass="select" disableRipple (selectionChange)="onChange()" [(value)]="selected" disableOptionCentering>
<mat-select-trigger>{{selected}}</mat-select-trigger>
<!-- mat-option below is required to render ng-content in mat-select. this is an ugly hack and there might be a better workaround for this -->
<mat-option [value]="" style="display: none;"></mat-option>
<ng-content></ng-content>
</mat-select>
有什么办法可以使这项工作或mat-select
根本不工作ng-content
?
我知道我可以使用@Input()
将选项传递给组件,但我认为使用ng-content
.
编辑:似乎我实际上可以选择项目。问题是我可以选择多个选项并且会产生连锁反应,即使disableRipple
我的mat-select
.
解决方案
有一个解决方法。将 ng-content 放在隐藏的 div 中并创建询问 ContentChildren(MatOption) 的选项,请参阅stackblitz中的示例
该组件是
import {Component, ContentChildren, AfterViewInit, QueryList} from "@angular/core";
import { MatOption } from "@angular/material/core";
@Component({
selector: "custom-select",
template: `
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select>
<ng-container *ngIf="yet">
<mat-option *ngFor="let option of options" [value]="option.value">
{{ option.viewValue }}
</mat-option>
</ng-container>
</mat-select>
</mat-form-field>
<div style="display:none" *ngIf="!yet">
<ng-content></ng-content>
</div>
`
})
export class CustomSelect implements AfterViewInit {
@ContentChildren(MatOption) queryOptions: QueryList<MatOption>;
options: any[];
yet: boolean;
ngAfterViewInit() {
this.options = this.queryOptions.map(x => {
return { value: x.value, viewValue: x.viewValue };
});
setTimeout(() => {
this.yet = true;
});
}
}
使用
<custom-select>
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</custom-select>
推荐阅读
- python - OSError:[Errno 30] 只读文件系统:'/storage/data/oxford-iiit-pet/export.pkl'(使用 fastai 库)
- python - 列表理解结合嵌套列表中的 2 个元素
- amazon-web-services - Spark:如何有效地将数据帧写入 S3
- r - 如果行包含字符串,R Shiny 反应过滤
- angular - 出现错误:使用 FormGroup 创建动态表单时找不到具有名称的控件:'' Angular
- c++ - 复制对象指针数组时出现CUDA cudaMemcpu分段错误
- android - AzureDevOps Android Pipeline zipalign - 失败,退出代码为 1
- java - 如果枚举常量是公共静态类型对象的引用,它们如何具有值
- python - 使用带有日期时间数据的 pcolor 和 pcolormesh 的着色选项 - 日期插值问题
- java - Spring Security:添加“伪登录”以更改用户信息