4

我想通过扩展 Angular 材质组件来创建自己的选择组件mat-select并使用我的自定义app-select组件,如下所示

<app-select>
  <mat-option>Value1</mat-option>
  <mat-option>Value2</mat-option>
  <mat-option>Value3</mat-option>
  <mat-option>Value4</mat-option>
</app-select>

我在 stackblitz 中做了一个例子,我几乎让它工作。我遇到的问题是选择选项后下拉面板不会关闭。

https://stackblitz.com/edit/angular-vdyjcy?file=src%2Fapp%2Fselect%2Fselect.component.html

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-select',
  templateUrl: './select.component.html',
  styleUrls: ['./select.component.css']
})
export class SelectComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
<mat-form-field>
  <mat-select>
    <mat-option>
      None
    </mat-option>
    <ng-content></ng-content>
  </mat-select>
</mat-form-field>

4

2 回答 2

0

您将需要扩展 MatSelect

@Component({ ... 提供者: [{ 提供: MatFormFieldControl, useExisting: E​​filingSelect }] })

导出类 SelectComponent 扩展 MatSelect { ... }

MatSelect 将实现 OnInit

如果要在 mat-form-field 元素中使用组件,可能需要添加提供程序

于 2019-08-22T21:30:01.257 回答
0

这不是对您问题技术性的直接回答,但还有另一种方法可以实现您想要实现的目标。

像这样将选项作为数组传递

class ParentComponent {
  public options = [
    'Value1',
    'Value2',
    'Value3',
    'Value4',
    'Value5'
  ];
}
<app-select [options]="options">
</app-select>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-select',
  templateUrl: './select.component.html',
  styleUrls: ['./select.component.css']
})
export class SelectComponent implements OnInit {

  @Input() options: string[];

  constructor() { }

  ngOnInit() {
  }

}
<mat-form-field>
  <mat-select>
    <mat-option>
      None
    </mat-option>
    <mat-option *ngFor="let option of options">{{ option }}</mat-option>
  </mat-select>
</mat-form-field>
于 2019-07-10T13:33:11.467 回答