Issue with Angular 7: In a ReactiveForm, mat-select does not allow setting a default option without using ngModel

I have a Angular 7 app where I am implementing some reactive forms.

The initialization of my reactive form looks like this:

private initFormConfig() {
    return this.formBuilder.group({
      modeTransfert: [''],
      modeChiffrement: [''],
    });
  }

Within my form, there are various inputs and mat-select elements:

<div class="form-inline form-group">
          <label class="col-md-2 justify-content-start">Target URL</label>
          <input  id="urlCible"
                  type="text"
                  maxlength="200"
                  ngDefaultControl
                  formControlName="urlCible"
                  class="col-md-6 form-control"/>
        </div>

        <div class="form-inline form-group">
          <label class="col-md-2 justify-content-start">Transfer Mode</label>
          <mat-form-field class="col-md-3" color="warn">
            <mat-select placeholder="Select transfer mode"
                        id="modesTransfert"
                        [(value)]="selectedModeTransfert"
                        ngDefaultControl
                        formControlName="modeTransfert">
              <mat-option *ngFor="let modeTr of modeTransfertData"
                          [value]="modeTr.value">
                {{modeTr.viewValue}}
              </mat-option>
            </mat-select>
          </mat-form-field>
        </div>

I am facing challenges in setting the default value for the select input. The main issues are:

  • The use of ngModel with ngFormControl (reactive form) is deprecated in Angular 7

  • Trying to patch its value like this leads to errors:

    this.addPefForm.patchValue({'modeTransfert': this.modeTransfertData[0].value});

This cannot be done initially in the onInit or AfterViewChecked hooks due to resulting error:

ParametragePefAdministrationFormComponent.html:107 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'mat-selected: false'. Current value: 'mat-selected: true'.
    at viewDebugError (core.js:20342)
    at expressionChangedAfterItHasBeenCheckedError (core.js:20330)
    at checkBindingNoChanges (core.js:20432)
    at checkNoChangesNodeInline (core.js:23305)
    at checkNoChangesNode (core.js:23292)
    at debugCheckNoChangesNode (core.js:23896)
    at debugCheckRenderNodeFn (core.js:23850)
    at Object.eval [as updateRenderer] (ParametragePefAdministrationFormComponent.html:107)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:23839)
    at checkNoChangesView (core.js:23193)
  • I also attempted to bind it using
    [(value)]="selectedModeTransfert"

However, none of these solutions worked.

Any suggestions?

Answer №1

When setting a default value for mat-select, make sure to specify it when initializing the reactive form like this:

  states = [
    {name: 'Arizona', abbrev: 'AZ'},
    {name: 'California', abbrev: 'CA'},
    {name: 'Colorado', abbrev: 'CO'},
    {name: 'New York', abbrev: 'NY'},
    {name: 'Pennsylvania', abbrev: 'PA'},
  ];

  form = new FormGroup({
    state: new FormControl(this.states[3].abbrev),
  });

<mat-select formControlName="state">
    <mat-option *ngFor="let state of states" [value]="state.abbrev">
        {{state.name}}
    </mat-option>
</mat-select>

By doing this, the value in your *ngFor loop will align with the value specified in the FormControl.

This method can also be used to display data fetched from an API and automatically fill in the fields with that information.

I hope this explanation clarifies things for you.

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

When using JSX, it's important to wrap adjacent elements within an enclosing tag to avoid errors. Make sure to properly wrap the JSX tags to

import React, { useState } from 'react'; import ReactDOM from 'react-dom'; function DisplayData(props) { //creating the DataList const dataList = data.map(data => ( <><span>{data.name}</span> nbsp; <span> ...

Having trouble debugging TypeScript files in Chrome following an Angular update

I have been experimenting with writing a basic app using Angular 4.2.5 to expand my knowledge. Previously, I was able to debug the TypeScript files in Chrome without any issues. However, after updating to Angular 5.2.7, I am no longer able to view the Type ...

Is it secure to use console.time() in a Node.js environment?

Looking at a small snippet of node.js code, here's what I have: console.time("queryTime"); doAsyncIOBoundThing(function(err, results) { console.timeEnd("queryTime"); // Process the results... }); Running this on my development system gives m ...

Is there a way to automatically add a div to the window as the user scrolls and then hide the div when they scroll back to the

Seeking assistance with creating a function that will add a 'sticky' class to the menu when the user scrolls down to the middle, and then append a div when the 'sticky' class is present. Currently facing issues where the div keeps appen ...

How can we efficiently load paginated data from a database while still implementing pagination using Angular Material?

I have a large table with more than 1000 entries that I want to display using a <mat-table></mat-table>. Since loading all the entries at once would be too much, I am looking to implement pagination and load only 20 entries per page. The chal ...

Enclose Angular $resource requests that do not return POST data

Currently, I am working on enhancing my $resource requests by implementing a straightforward wrapper. The primary objective is to incorporate some logic before the request is actually sent. For guidance, I referred to an informative article authored by Nil ...

AngularJS/Ionic: Issue with HTTP GET requests not completing within a specified timeframe

Attempting to populate options with specific values instead of undefined, but encountering a delay in retrieving the values after the select box has finished loading. https://i.stack.imgur.com/SpEFP.jpg To illustrate, here is the HTML code snippet: < ...

Leveraging Parameters from URL in Javascript

I'm facing an issue with my area shape, the href="/kosmetikstudios/deutschland/Bayern" tag seems to be causing a problem. I want to utilize the parameter "Bayern" (which is the last parameter in the URL). I need this to be dynamic. Below is my JavaS ...

Modify the data in a JSON array and receive the revised array using JavaScript

Within my JSON object, I have price values in numerical format. I am looking to convert these price values into strings within the same object My approach involves using the map function: var prods = [ { "id": "id-1", "price": 239000, "inf ...

SOLVED: NextJS restricts plugins from modifying HTML to avoid unnecessary re-rendering

My current scenario is as follows: I am in the process of developing a website using NextJS (SSR) I have a requirement to load a script that will locate a div element and insert some HTML content (scripts and iframes) within it. The issue at hand: It se ...

Utilizing a GET method with MongoDB

My front end has a link using axios with a placeID parameter: http://localhost:3001/api/getData?placeID=Uh8LPCRstLnJ-ZY3B41N9w I am trying to retrieve results based on the placeID in my database. I have made sure that there is data with the specific place ...

renewing a div element without the need to reload the entire webpage

I'm currently developing a setup process for configuring a database. My goal is to allow the user to progress through each phase without having to refresh the page. However, I've encountered an issue while trying to implement the .load() function ...

How can I move the cursor to the beginning of a long string in Mat-autocomplete when it appears at the end?

I'm struggling to figure out how to execute a code snippet for my Angular app on Stack Overflow. Specifically, I am using mat-autocomplete. When I select a name that is 128 characters long, the cursor appears at the end of the selected string instead ...

Is there a way to securely store my JWT Token within my application's state?

userAction.js -> Frontend, Action export const login = (userID, password) => async (dispatch) => { try { dispatch({ type: USER_LOGIN_REQUEST }); const url = "http://localhost:8080/authenticate/"; const ...

Tips for effectively structuring material-ui Grid in rows

I am currently using the material-ui framework to create a form. Utilizing the Grid system, I want to achieve the following layout: <Grid container> <Grid item xs={4} /> <Grid item xs={4} /> <Grid item xs={4} /> </Gr ...

What is the best way to adjust the width of a textarea based on its content

How can I dynamically set the width of a React Semantic UI textarea based on its content? Setting min-width doesn't seem to be working. Any suggestions? <Textarea key={idx} defaultValue={formattedText} className="customInpu ...

Unusual JavaScript Bug: Uncaught TypeError - Unable to access property 'url' of null

I encountered a peculiar JavaScript error. The following message appears in the console: Uncaught TypeError: Cannot read property 'url' of null (Line 83) The code on Line 83 looks like this: var image = '<img class="news_image_options ...

Error code E11000 is thrown due to a duplicate key in a Node.js application

Whenever I input data on the webpage, it syncs correctly with the database. However, when I attempt to fill out the same form again, an error occurs: { "code": 11000, "index": 0, "errmsg": "E11000 duplicate key error collection: test.creates i ...

Step-by-step guide on building a mat-table with nested attributes as individual rows

Here is the data structure I am working with: const families = [ { name: "Alice", children: [ { name: "Sophia" }, { name: "Liam" ...

Is it recommended to include modules in the Imports section of SharedModule in Angular?

Welcome to my SharedModule! import { CommonModule } from "@angular/common"; import { NgModule } from "@angular/core"; import { FormsModule, ReactiveFormsModule } from "@angular/forms"; import { IconModule } from "@my-app/components/icon/icon.module"; impo ...