The model fails to update when a blur event occurs

I am a beginner with Angular2 and I am currently working on creating a reactive form, specifically an interactive date input field.

Here is my HTML code:

<div class="date ui-input">
    <input type="text" name="dateD" [ngModel]="model.date | date:'dd'" (blur)="setDate($event.target.value, 'd')" maxlength="2" />
    <div>.</div>
    <input type="text" name="dateM" [ngModel]="model.date | date:'MM'" (blur)="setDate($event.target.value, 'm')" maxlength="2" />
    <div>.</div>
    <input type="text" name="dateY" [ngModel]="model.date | date:'y'" (blur)="setDate($event.target.value, 'y')" maxlength="4" />
</div>

And here is the related TypeScript code for setDate():

setDate(input:number, type:string[1]) {
    let min = 1;
    let max = 1;
    let fn = null;

    switch(type) {
        case 'd':
            max = 31;
            fn = 'setDate';
            break;
        case 'm':
            input -= 1;
            min = 0;
            max = 11;
            fn = 'setMonth';
            break;
        case 'y':
            min = 1990;
            max = 9999;
            fn = 'setFullYear';
            break;
    }
    if(input < min) {
        input = min;
    }
    else if(input > max) {
        input = max;
    }

    if(fn)
        this.model.date[fn](input);

    console.log(this.model.date);
}

The model is updating correctly, as confirmed by console.log(). However, the view does not reflect these changes.

I expected the input fields to display the correct date based on the date pipe, but it seems that my expectations were wrong. In Angular 1.x, things were different, but I managed to achieve my goal back then.

Any suggestions or advice? Is there a way to manually update the model?

Answer №1

Directly manipulating the value property of a form field does not trigger an update. To properly update the form field, use patchValue. More information can be found at this link

$event.target.patchValue({dateY: value});

Here is an example of implementing it in HTML:

<form [formGroup]="myForm">
    <input formControlName="myValue" (ionChange)="recalculate($event)">
</form>

In TypeScript:

public recalculate(e) {
    let currentValue = this.myForm.controls.get(myValue).value;
    this.myForm.patchValue({ myValue: currentValue / 10 });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting jQuery Div Separation Problem

Currently, I am working on implementing resizable sidebars using jQuery and potentially jQueryUI. However, I am encountering an issue with the resizing functionality. Specifically, the right sidebar is causing some trouble in terms of proper resizing, wher ...

struggling with handling form data in Express/Node application

Currently this is my setup: Below is the Post method I am using app.post('/barchartentry', function(req, res){ res.render('barchart', { title: 'EZgraph: Bar Chart', barValues: req.body.myInputs, labelValues: req.body ...

Why is my JavaScript code functioning properly on jsfiddle but failing to work when run locally?

After recently creating JavaScript code that allows for form submission using the <form> tag, I encountered an issue when trying to implement it within an HTML page. Here is a snippet of the code: <script type="text/javascript"> var m ...

Please ensure that the table contains all the records corresponding to the respective days

I am struggling with figuring out how to display a record of classes in my table view. The UX prototype I need to follow is shown https://i.stack.imgur.com/CISYn.png (the days of the week are in Portuguese: horario = time, segunda = Monday, terça = Tuesda ...

Location-based services: Updating the position of a Google Maps marker without refreshing the entire map interface

How can I update only the marker on a map when the device is in motion or has increased accuracy? I want to reload the map when the position changes, but only move the marker. Below is the code snippet that I currently have: if (navigator.geolocation) { ...

Utilize jQuery to apply inline styles to dynamically created div elements

I am attempting to apply inline styles to a div using jQuery. The current state of the div, as seen in Firebug, is shown below: https://i.sstatic.net/rqhIc.jpg My goal is to retain the existing CSS while adding margin-left:0 and margin-right:0 to the cur ...

Exploring the capabilities of @angular/cli and integrating it with non-angular scripts can significantly

After upgrading my application to Angular 5, I decided to experiment with @angular/cli instead of using different webpack configs from the Angular starter package like I did previously. Our build process is fairly simple except for one aspect that I' ...

CSS struggles after implementing conditional checks in return statement for an unordered list

I'm encountering a CSS issue with the header section. When I include the following code snippet in my code to display a tab based on a condition, the entire header list doesn't appear in a single horizontal line: <div> {isAdmin(user) ? ...

Customizing Bootstrap Vue to prevent tooltips from opening on hover

I am currently using a tooltip similar to the example shown on Toggle Tooltip: <template> <div class="text-center"> <div> <b-button id="tooltip-button-1" variant="primary">I have a tooltip</b-button> </div& ...

A guide on crafting a test scenario for an AngularJS controller using the Jasmine framework

I recently created an angular module called userModule.js 'use strict'; angular.module('users', ['ngRoute','angular-growl','textAngular','ngMaterial','ngMessages','ngImgCrop', ...

Modify the content in the v-navigation-drawer upon clicking

I am currently working on a project with a v-navigation-drawer and two buttons. The first button is designed to open the drawer, while the second one should change the content of the drawer without closing it. I want the content to update instantly without ...

Navigating to a webpage using a dropdown menu selection and a button press

I'm new to Angular and wondering if it's possible to select an option from a dropdown menu and then be redirected to a specific page based on that selection <mat-label >Login As</mat-label> <mat-select> ...

JQuery UI Autocomplete: Results, Ctrl + A and Delete

I am currently designing a form that allows users to add members to a project. Only members with existing profiles in the system can be added. The form includes an input field for the member's name and a select box for their position, which is initial ...

Unable to access a particular page on Angular

I am facing an issue while trying to navigate to a specific page in my angular app. I am attempting to navigate to (tabs/market-palce/fornecedores) from app.component.ts using my routing Modules. Error: Cannot match any routes. URL Segment: 'tabs/mar ...

The TypeScript error message indicates that the property 'forEach' is not found on the 'FileList' type

Users are able to upload multiple files on my platform. After uploading, I need to go through each of these files and execute certain actions. I recently attempted to enhance the functionality of FileList, but TypeScript was not recognizing the forEach m ...

Host several Node.js applications concurrently on one server

Attempting to run multiple Node.js apps on a single server has been my focus lately. I have been exploring solutions for similar queries here and have reached some progress. Let's consider the scenario where I have two apps, each serving different HTM ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

What is the best approach to sending numerous queries from a single endpoint using Express?

I am attempting to perform multiple database queries and create an object that stores each response from the database in a specific field. Below is the code I have written: router.post('/search', (req, res) => { var collection = db.get(). ...

JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP. This is an example of my json: { 'username': 'Karl', 'email': '<a href=" ...

When working with Typescript and Vue.js, it's important to ensure that properties are initialized before

Check out the following code snippet: export default class PrimitiveLink extends Vue { style = { // Reset display: 'inline-block', textDecoration: 'none', outline: 'none', // Theme ...this.themeStyle ...