mat-select and event change

0

I'm trying to start a mat-select, I'm handling the data well, but I want to do something when one of the values is selected.

I use angular 6, this is my ts code:

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

When I select a value of the select, nothing happens ...

    
asked by Yoedusvany Hdez 22.05.2018 в 22:51
source

3 answers

1

Instead of (change) use (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>
    
answered by 16.07.2018 в 14:14
0

You have two options:

1. Use selectionChange in the template

You can use the change directive selectionChange directly in the mat-select of your HTML template and use the object $event to take the selected value, that is (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. Use valueChange in the modal

The other option is to use valueChange in your object _selectPaymentPlanForm of your modal (not in your HTML) '. valueChange returns an Observable from which you can subscribe to changes in a form or control. In this case we need the control change 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
}
    
answered by 16.07.2018 в 14:58
0

Hello, I solved this problem in the following way:

Add a click-type event in the mat-option, so when you click on any option you will have the id or the value of it.

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

In the ts the value is captured in the function "functionName" and that's it.

    
answered by 04.08.2018 в 22:19