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

405 we're sorry, but the POST method is not allowed on this page. This page does

I'm currently working on a small Form using the kit feature Actions. However, I'm facing an issue when trying to submit the form - I keep receiving a "405 POST method not allowed. No actions exist for this page" error message. My code is quite st ...

Implementing ng-if with asynchronous functions: A step-by-step guide

The objective here is to display an image in a template only if the ratio of its dimensions is greater than 2. <img class="main-img" ng-if="showImage($index)" ng-src="{{item.img}}"> Implementation: $scope.showImage = function(index) { var img ...

Choose the offspring of an element using jQuery

Currently, I have a function set up to open a modal dialog and populate it with information from the 'dblclicked' node: $(function(){ $(".delete").live('dblclick', function () { var id = $(this).attr('id'); ...

Angular 6 triggers NavigationCancel event when encountering valid guards

I'm encountering difficulties with the Angular router while trying to navigate to a specific state. Despite my attempts to utilize a custom guard with canLoad() and canActivate() functions that return true, I have not been successful. The Angular do ...

Guide on grabbing characters/words typed next to # or @ within a div element

Within a div element, I have enabled the contenteditable property. My goal is to capture any text input by the user after typing '#' or '@' until the spacebar key is pressed. This functionality will allow me to fetch suggestions from a ...

Using the DatePicker component with non-escaped Latin alphabet characters in date-fns for ReactJS

While attempting to integrate the DatePicker component from Material UI into my React project, I encountered an error. Although many attributed the issue to a version discrepancy, what ultimately resolved the problem for me was assigning a value to the Da ...

Transferring MongoDB information to a Jade template in an ExpressJS application

Hey there, hoping you can assist me with a query issue I'm facing. To give you some context, I am querying a MongoDB collection and trying to pass the results back to a Jade view. app.helpers({ clients: function(){ users.find({uid:req.session.u ...

Navigating the Terrain of Mapping and Filtering in Reactjs

carModel: [ {_id : A, title : 2012}, {_id : B, title : 2014} ], car: [{ color :'red', carModel : B //mongoose.Schema.ObjectId }, { color ...

"Patience is key as we await the resolution of a promise within the confines of an emitter

My goal is to wait for the promise to be resolved before continuing when the someevent event is fired. However, even though I use a then in my code snippet below, it seems that the process shuts down before the slowFunctionThatReturnsPromise is resolved, ...

The findByIdAndUpdate() function lacks the ability to modify the collection

I'm encountering an issue when trying to update a product using mongodb and redux. It seems that the database is not reflecting the changes after I attempt to update the product. Can someone please assist me with this problem? Here is my product.js f ...

Is there a way to automatically change the display of an element once the user has closed the menu?

How can I ensure that the display of an element remains unchanged when a user opens and closes my website menu using JavaScript? ...

Guide on removing a key from an object in TypeScript

My variable myMap: { [key: string]: string[] } = {} contains data that I need to modify. Specifically, I am trying to remove a specific value associated with a certain key from the myMap. In this case, my goal is to delete value1 from myMap[Key1]. Despit ...

Develop a game timer using CreateJS

Looking for advice on the most effective method to create a timer clock using Createjs. I've attempted to reference HTML elements with DOMElement in the past, but encountered difficulties. Essentially, I need to display a timer within a container so p ...

What could be the reason for my Express server returning a 404 error for all files other than index.html?

Currently, I am delving into Node.js with Express in order to set up a small server for educational purposes. Strangely, every request made to files linked within my index.html file, such as the .css, .js, and image files, results in a response code 404. ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

Display information on a table using AJAX within the current webpage

I am encountering an issue with ajax on the same page. Below is my code: $.ajax({ type: "POST", url: "test.php", dataType: 'json', data: {}, success: function (data) { ...

Executing a method in an applet using JavaScript

I am trying to print some information using an applet. The applet is located in the signed qds-client.jar file and has the following code: public class PrintText extends Applet implements Printable { private ClientAccount clientAccount; public Client ...

JavaScript: Exporting and Utilizing a Function within a Model.js File

Coming from a background in PHP OOP development, I am aware that there are various methods to create classes in JavaScript. I require assistance from a JavaScript developer to resolve this particular issue. Here is the situation: I am building an AWS lamb ...

Error while conducting unit testing: Element 'X' is unrecognized

While running the command npm run test, I encountered a specific error in my terminal: 1. If 'app-general-screen' is an Angular component, then verify that it is a part of an @NgModule where this component is declared. 2. If 'app-general-sc ...

The requested path /releases/add cannot be located

In my CRUD application, I have a feature that allows users to create releases by adding a version and description. This is achieved through a button and input fields for the details. <button (click)="addRelease(version.value, description.value)" [d ...