首页 > 解决方案 > 是否可以使用 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.

标签: angulartypescriptangular-material

解决方案


有一个解决方法。将 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>

推荐阅读