Search code examples
angularangular-materialhiddenangular-ng-ifmat-select

Add mat-option conditionally to mat-select


Remove some parameters inside a mat-select

Hi everyone! I'm bringing some parameters (7) from a database but I only need to work with 4, so that when displaying the list of the mat-select it shows me only the 4, not 7. I have tried to hide them with the [hidden] option but I really want to remove them and my browser doesn't see them, how could I do it? I am quite a newbie to Angular. I have read that with an * ngIf but I don't know how. I appreciate any help!

HTML:

<td>
  <mat-select
    placeholder="Tipo trámite"
    name="tipoTramite"
    [(ngModel)]="tipoTramiteValue"
    (change)="onChange(tipoTramiteValue)"
  >
    <mat-option
      *ngFor="let tipoTramite of listTiposNovedad"
      [value]="tipoTramite.nombreParametro"
      [hidden]="tipoTramite.nombreParametro == 'TERMINACIÓN ANTICIPADA' || tipoTramite.nombreParametro == 'PRÓRROGA'  || tipoTramite.nombreParametro == 'SUSPENSIÓN'"
      >{{tipoTramite.nombreParametro}}</mat-option
    >
  </mat-select>
</td>

TS:

export class SolicitudFormat implements OnInit {
  tipoNovedad;
  listTiposNovedad;

  constructor(
    private dialog: MatDialog,
    public datePipe: DatePipe,
    public adminCTService: AdminCtserviceService,
    public parametroService: ParametroService
  ) {
    this.parametroService.listNovedadesContrato().subscribe((response) => {
      this.listTiposNovedad = response;
    });
  }
}

Solution

  • You can do it using *ngIf this way

    *ngIf="condition" (where condition is the condition on which you want to render the element)

    <td>
              <mat-select placeholder="Tipo trámite" name="tipoTramite" [(ngModel)]="tipoTramiteValue"  (change)="onChange(tipoTramiteValue)">
    <ng-container *ngFor="let tipoTramite of listTiposNovedad">
                <mat-option *ngIf="!(tipoTramite.nombreParametro == 'TERMINACIÓN ANTICIPADA' || tipoTramite.nombreParametro == 'PRÓRROGA'  || tipoTramite.nombreParametro == 'SUSPENSIÓN')" [value]="tipoTramite.nombreParametro" >{{tipoTramite.nombreParametro}}</mat-option>
              </mat-select>
    <ng-container>
    </td>