Angular2 Reactive Form: Implementing field validation using *ngIf

My form includes fields such as md-select and md-radio-button. The radio button options are dependent on the selection made in the md-select field. To see an example, please check out this plunker.

I have set the sub-organism radio-button field to be required in the form. It works correctly upon initial loading. However, if a sub radio button option is selected and then the organism select box is changed, the form remains valid even without a valid sub-organism value. I need the form to become invalid if no sub radio button is checked. Any suggestions would be appreciated.

Question 2: In the plunk provided, there are lines commented out after line 47 in app.component.ts. Uncommenting these lines will set default values for the fields. This results in the sub-organism radio buttons being displayed while the select box remains blank. Although the reason for displaying the sub-organism fields is due to a selected value, it seems that the option is not being selected for organisms in the md-select field. Any insights into this issue?

Answer №1

To ensure that the selection in md-select triggers a reset of the selected.sub_organism_id value to null if the form was validated, add a change event handler.

Code examples:

HTML:

<md-select [formControl]="form.controls['organism']" 
           style="width:100%;" 
           [(ngModel)]="selected.organism_id" 
           (change)="resetForm($event)">
  <md-option *ngFor="let organism_id of getIds()" [value]="organism_id">
    {{ organisms[organism_id].name }}
  </md-option>
</md-select>

TypeScript:

resetForm(event){
  if(this.form.valid){
    this.selected.sub_organism_id = null;
  };  
}

Edited Plunk

Update:

In response to @WillHowell's comment about how "md-select compares values by object reference not object value," it is true. By modifying your data to an array-object relation, you can see that the default value in md-select works correctly here.

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

The array isn't showing any values on the screen

I have been working on a program that will collect values from text boxes and store them in an array. Then, I want to display these values in a table format with the total miles added up. The total miles should be highlighted based on their value. However, ...

JavaScript isn't triggering the callback function after the AJAX operation is finished

Here is some code snippet from an ASP.NET MVC View: <% using (Ajax.BeginForm("AddCommunity", new AjaxOptions { UpdateTargetId = "community-list", OnSuccess = "BindCommunityHover" })) { %> Add Community: <input type="text" id="com ...

What is the best way to transfer a variable from an @Input property to a service within an Angular2 component?

I'm tackling what seems like a simple task, but I'm struggling to figure it out. My issue is this: How can I successfully pass a variable from @Input to a service in an Angular2 component? (Code has been simplified) This is my current component ...

The ion-nav-buttons controller is triggering twice

Seeking a solution for displaying badges based on need inside the ion-nav-buttons. However, facing an issue where the controller inside the ion-nav-buttons is triggered twice. Interestingly, placing it outside the ion-nav-buttons resolves this problem. Fo ...

Utilizing the components within the range set by paper.setStart() and paper.setFinish() in Raphaels

My question has two parts - the first and second part. Let's consider an example code that I am working on. I am creating a map of my country with regions, and I want to perform actions on the entire map such as scaling or translating (as seen in the ...

creating a randomized location within an HTML element using JavaScript

Trying to figure out how to randomly generate a position within an HTML div. I've come up with a JavaScript function that looks like this: function randomInRange(min, max) { return(Math.floor((Math.random() * (max - min) + 1) + min)); } My ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

Loading an Angular form dynamically upon button click

Looking to develop a dynamic page where various forms can be loaded upon button press. Each button triggers the addition of a new form with unique input fields corresponding to that button. The objective is to ensure that forms load in the sequence of butt ...

Ways to leverage the power of Reactivity APIs in Vue.js

In my Vue application, I am trying to create a Drop Down Menu by using a variable called "showDropDown". The idea is to use a v-if directive to check if the value of showDropDown is true, and then display the menu accordingly. Additionally, I want to imp ...

Converting XML schema to JSON format using Node.js

I am attempting to loop through or access keys of a JSON object that was created from an XML object in node.js. Here is my current code: var fs = require('fs'); var parser = require('xml2json'); var xsd = require('libxml-xsd&apos ...

What is the best way to pass values between JSP Expression Language and Javascript?

I have a request object with the following content: List<Integer> list What is the best way to loop through this list using JavaScript? I am interested in obtaining the values of each element within the list. Note that these list values are not cu ...

Using the map function in React, you can tie the state to a conditional statement

I am facing an issue with my post list where I want to show comments only when a post is toggled. However, I cannot access the state in my method that checks if the post is toggled or not. Shouldn't arrow functions automatically bind the context? va ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

Session-based Authorization

I'm completely new to working with express.js, and I've been facing an issue while trying to create a session-cookie after logging in. Even though I can initiate the session and successfully log in, the session data doesn't carry over to the ...

How to retrieve the button value in HTML

One of the HTML components I am working with is a button that looks like this: <button>Add to cart</button> My goal is to retrieve the text within the button, which in this case is "Add to cart." To achieve this, I need to extract this value ...

Error: The property 'case sensitive routing' cannot be accessed because it is undefined

Task at hand: Running ExpressJS port using Node.js, nodemon, and lib. Operating System: Windows 10 Home x64 Node.JS Version: Lts The Challenge: Getting the ExpressJS port to run successfully. Current Issue: Encountering an internal file error, potentiall ...

Change the websocket origin to localhost in a javascript setting

My server is hosting the domain example.com. Every time a user loads a page on this server, it utilizes a WebSocket client in JavaScript to connect to another WebSocket server. However, the other server has CORS enabled, which prevents the connection bec ...

Enhancing functionality with extra JavaScript tags in next.js

Recently, I delved into programming with react & next.js after previously working with node.js. It didn't take long for me to create my first application, but upon inspecting the page, I noticed an abundance of extra JavaScript code (see image below). ...

What is the best method for showcasing various content using a uniform accordion style in React?

What is the most efficient way to display various content within multiple accordions? view image description here This is the current approach I am taking in my project, where shipping information and delivery options will involve different textboxes, labe ...

How can objects be outlined in a projected context using a shader?

I am currently experimenting with modifying the OutlinePass in threejs to create outlines of connected objects in clip space (after applying the projection matrix). While these objects may appear separate in 3D space, they are considered connected after pr ...