3
votes

I would like to create my own select component by extending Angular material component mat-select and use my custom app-select component like below

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

I have made an example in stackblitz where I almost got it to work. The issue Im having is that the dropdown panel wont close after selecting an option.

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>
2
don't wont to cause any doubts but you also lost some focus and keyboard related functionalityXesenix

2 Answers

0
votes

This is not a direct answer to the technicalities of your question, but there is another way to achieve what you are trying to achieve.

pass the options as an array like this

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>
0
votes

You will need to extend MatSelect

@Component({ ... providers: [{ provide: MatFormFieldControl, useExisting: EfilingSelect }] })

export class SelectComponent extends MatSelect { ... }

MatSelect will implement OnInit

You might need to add a provider if you're going to use the component in a mat-form-field element