Balázs Fehér
Balázs Fehér

Reputation: 344

How to update value using angular material after picking value?

I would like to use angular material Datepicker to select dates. Once the date is picked I would like to update a value. The below code works (i.e. value gets updated) if I type something the input field of the Datepicker, but not when picking the date through the Datepicker toggle.

My best guess is that I should use something other than (input)="updateDate($event)" in the html.

app.component.html:

<mat-form-field>
        <mat-label>Choose start date</mat-label>
        <input matInput [matDatepicker]="picker" (input)="updateDate($event)">
        <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
        <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

app.component.ts:

updateDate(event: any) {
    this.exam.date = event.target.value;
  }

Upvotes: 0

Views: 2680

Answers (2)

Marrds
Marrds

Reputation: 65

<mat-form-field>
    <mat-label>Choose start date</mat-label>
    <input matInput [matDatepicker]="picker" (dateChange)="addEvent($event)"">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>

ts example

addEvent(event: MatDatepickerInputEvent<Date>) {
  this.exam.date = event.target.value;
}

Upvotes: 2

Micha
Micha

Reputation: 924

you can use changeDetectorRef, see this example: --> in onChange-event the detectChange-process is triggert explicit. See this example also on my website.

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { CalcComponent } from '../calc-component';

@Component({
  selector: 'app-circular-area',
  templateUrl: './circular-area.component.html',
  styleUrls: ['./circular-area.component.scss']
})
export class CircularAreaComponent implements OnInit {
  public render: Boolean;
  public radius: number;
  public r: number;
  constructor(**private cdRef: ChangeDetectorRef**) { }

  onChange(event: any, r: number) {
    console.log(r);
    this.r = Number(r);
    this.render = true;
    this.cdRef.detectChanges();
    this.render = false;
  }

  ngOnInit() {
    this.render = false;
  }
}

<div class="mat-elevation-z8">
    <form  (change)="onChange($event,r.value)">  
        <fieldset class="material">
          <label>Radius</label>
          <hr>
          <input #r type="number" placeholder={{radius}} autocomplete="on" value = 5 required> 
        </fieldset>
        <ng-container *ngIf="!render">
           <app-calc-component value={{r.value}} selCalc='circulararea'></app-calc-component>
      </ng-container>
      </form>
 </div>

Hope you can work with this approach!

Upvotes: 1

Related Questions