3

estoy tratando de hechar a andar un mat-select, cargo los datos bien, pero quiero hacer algo cuando se seleccione uno de los valores.

Utilizo angular 6, este es mi codigo del ts:

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

//---------------------------
// Router
//---------------------------
import { Router }               from '@angular/router';

//---------------------------
// Angular Forms
//---------------------------
import { FormBuilder }          from '@angular/forms';
import { FormGroup }            from '@angular/forms';
import { Validators }           from '@angular/forms';
import { FormControl }          from '@angular/forms';
import { ValidatorsLibrary }    from '../../../../core/services/validators.service';

import { SecurityService }      from '../../../../services/security.service';
import { GlobalsService }       from '../../../../core/services/globals.service';
import { LogService }           from '../../../../core/services/log.service';
import { UserService }          from '../../../../services/user.service';
import { User }                 from '../../../../models/user.model';
import { Plan }                 from '../../../../models/interfaces/plan.interface';


@Component({
  selector: 'app-select-comp',
  templateUrl: './select-comp.component.html',
  styleUrls: ['./select-comp.component.css']
})

export class Comp...Component implements OnInit {
    public plans                    : Plan[] = [];
    public promotionalCode          : string;
    public totalSubscription        : number = 0;    
    public _selectPaymentPlanForm   : FormGroup;
    public classButtonColor         : string;
    public selectedPlan             : Plan;

    private routerService   : Router;
    private securityService : SecurityService;
    private globalsService  : GlobalsService;
    private logService      : LogService;
    private userService     : UserService;
    private fb              : FormBuilder;
    private validator       : ValidatorsLibrary;

    constructor(
        fb: FormBuilder,
        rt: Router,
        ss: SecurityService,
        ls: LogService,
        us: UserService,
    ) {
        // Services
        this.securityService    = ss;
        this.routerService      = rt;
        this.logService         = ls;
        this.globalsService     = GlobalsService.getInstance();
        this.userService        = us;
        this.fb                 = fb;

        this.createForm();
        

    }

    ngOnInit() {
        this.classButtonColor = 'primary';
        this.plans = [
            { id: 1, name: 'abc', price: 40, description: 'desc1...' },
            { id: 2, name: 'qwe', price: 9.95, description: 'desc2...' },
            { id: 3, name: 'asd', price: 19.95, description: 'desc3...' },
        ];
    }

    createForm()
    {
        this._selectPaymentPlanForm  = this.fb.group({

            'plans'                 : ['', Validators.compose([                                      
                                      Validators.required
                                     ])
                                    ],

            'promotionalCode'       : ['', Validators.compose([                                      
                                      Validators.minLength(3)
                                     ])
                                    ],
            'totalSubscription'     : ['', Validators.compose([                                      
                                        Validators.minLength(3)
                                       ])
                                    ],                        


        });
    }

select(plan)
{
    console.log(plan)
}

    
}
<form [formGroup]="_selectPaymentPlanForm" (ngSubmit) = "cmdSelectPaymentPlan_click()" novalidate>
  <mat-form-field class="input-width">
    <mat-select placeholder="Plans" formControlName="plans" (change)="select(plan)"  required>
      <mat-option *ngFor="let plan of plans" [value]="plan.name">
        {{ plan.name }}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <br/>
  ...
</form

Cuando selecciono un valor del select no ocurre nada...

3 respuestas 3

10

En lugar de (change) usa (selectionChange)

 <form [formGroup]="_selectPaymentPlanForm" (ngSubmit) = "cmdSelectPaymentPlan_click()" novalidate>
    <mat-form-field class="input-width">
        <mat-select placeholder="Plans" formControlName="plans" (selectionChange)="select(plan)"  required>
            <mat-option *ngFor="let plan of plans" [value]="plan.name">
              {{ plan.name }}
            </mat-option>
        </mat-select>
    </mat-form-field>
    <br/>
    ...
 </form>
0
4

Tenés dos opciones:

1. Usar selectionChangeen la plantilla

Podés usar la directiva de cambio selectionChange directamente en el mat-select de tu plantilla HTML y usar el objeto $event para tomar el valor seleccionado, o sea (selectionChange)="select($event.value)"

<form [formGroup]="_selectPaymentPlanForm" (ngSubmit)="cmdSelectPaymentPlan_click()" novalidate>
    <mat-form-field class="input-width">
        <mat-select placeholder="Plans" formControlName="plans" (selectionChange)="select($event.value)"  required>
            <mat-option *ngFor="let plan of plans" [value]="plan.name">
              {{ plan.name }}
            </mat-option>
        </mat-select>
    </mat-form-field>
    <br/>
    ...
</form>

2. Usar valueChange en el modal

La otra opcion es usar valueChange en tu objeto _selectPaymentPlanForm de tu modal (no en tu HTML)'. valueChange te devuelve un Observable desde el cual te poés subcribir a los cambios de una forma o de un control. En este caso necesitamos el cambio del control plans.

createForm() {
    this._selectPaymentPlanForm  = this.fb.group({
       'plans'                 : ['', Validators.compose([                                      
                                  Validators.required
                                 ])
                                ],
       // ... el resto de los controles                    
    });

    this._selectPaymentPlanForm.get('plans')              // Tomamos el control 'plans'
       .valueChanges.subscribe( valor => select(valor) ); // Subscribimos a los cambios
}
1

Hola hace rato resolvi este problema de la siguiente manera:

Adicione un evento tipo click en el mat-option, asi cuando se le de click a cualquier option tendre el id o el valor de la misma.

 <mat-option (click)="functionName(somevar) [value]="valueVar">

En el ts se captura el valor en la funcion "functionName" y listo.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.