簡體   English   中英

如何在Material Angular 8中擴展墊選擇組件?

[英]How can I extend mat-select component in Material Angular 8?

我想通過擴展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> 

這不是對問題的技術性的直接答案,但是有另一種方法可以實現您要實現的目標。

將選項作為這樣的數組傳遞

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>

您將需要擴展MatSelect

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

導出類SelectComponent擴展了MatSelect {...}

MatSelect將實現OnInit

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM