Getting a JSON value and saving it to a variable in Angular 4

Here is the JSON structure:

{
  "Semester": [
    {
      "queueName": "Science",
      "totalCount": 300,
      "unassignedCount": 10,
      "subjectDetails": [
        {
          "subjectName": "Chemistry",
          "sectionOne": 100,
          "sectionTwo": 50,
          "onTrackTradeCount": 150
        },
        {
          "subjectName": "Biology",
          "sectionOne": 100,
          "sectionTwo": 50,
          "sectionThree": 150
        }
      ]
    },
    {
      "queueName": "Arts",
      "totalCount": 300,
      "unassignedCount": 10,
      "subjectDetails": [
        {
          "subjectName": "Indexing",
          "sectionOne": 100,
          "sectionTwo": 50,
          "sectionThree": 150
        }
      ]
    },
    {
      "queueName": "Humanity",
      "totalCount": 300,
      "unassignedCount": 10,
      "subjectDetails": [
        {
          "subjectName": "Indexing",
          "sectionOne": 100,
          "sectionTwo": 50,
          "sectionThree": 150
        }
      ]
    }
  ]
}

The Semester values are displayed in a multi-select dropdown using matSelect from Angular Material. When someone selects a particular semester, the corresponding subjectName should be displayed in another dropdown.

I am struggling with implementing this functionality, any help would be appreciated.

Answer №1

It seems like you are looking to implement a dropdown feature for semester items and then another dropdown for subjects based on the selection from the first dropdown.

To achieve this in your *.component.html file:

<mat-form-field>
 <mat-select placeholder="Semester" [(value)]="chosenSub">
  <mat-option *ngFor="let sem of Semester" [value]="sem.subjectDetails">
   {{ sem.queueName }}
  </mat-option>
 </mat-select>
</mat-form-field>
 <br>
<mat-form-field>
 <mat-select placeholder="Subject">
  <mat-option *ngFor="let sub of chosenSub" [value]="sub.subjectName" >
   {{ sub.subjectName }}
  </mat-option>
 </mat-select>
</mat-form-field>

In your *.component.ts file:

chosenSub = '';

You can view a live demo of this implementation on StackBlitz.

Here is an illustration of how it works: https://i.sstatic.net/ZopfX.png

Answer №2

If I understand correctly, you will need to utilize something similar to the code snippet below for your template:

<mat-form-field>
<mat-select>
  <mat-option *ngFor="let sem of Semester" [value]="sem.queueName" formControlName="firstDropdown">
    {{ sem.queueName }}
  </mat-option>
</mat-select>
<mat-select>
  <mat-option *ngFor="let sub of selectedSemester.subjectDetails">
    {{ sub.subjectName }}
  </mat-option>
</mat-select>
</mat-form-field>

In the corresponding typescript file, you can bind the two together so that selectedSemester is set to Semester[0] initially and updates when the value in the first dropdown changes. You may prefer using a class-based form and subscribing to the change observable to update the selectedSemester. Here's an example of how it could be done:

ngOnInit() {
  this.selectedSemester = this.Semester[0]
  this.myForm.valueChanges.subscribe(
    data => { 
       const temp = this.myForm.get('firstDropdown').value
       this.selectedSemester = this.Semester.find(
         el => el.queueName === temp
       )
     }
  )

I hope this provides some guidance, but the specific implementation will vary based on your application.

Best of luck!

Answer №3

In the component, you can set up your form like this:

 public form: FormGroup = new FormGroup({
    semester: new FormControl(''),
 });

To populate a dropdown with mat-select options based on the selected value from another dropdown, use an Array Object for semester.subjectDetails.

 <mat-select formControlName="semester" required placeholder="Semester">
            <mat-option *ngFor="let semester of JsonSemester"
                        [value]="semester.subjectDetails">
              {{ semester.queueName}}
            </mat-option>
    </mat-select>

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

Is there a way to verify whether a key within an Interface corresponds to a class that is a subclass of a specific Parent

Is there a method in typescript to ensure that a property in an interface must be of type "child subclass C, which extends class P"? example.ts import { P } from '/path/to/types' class C extends P { ... } types.ts // `C` cannot be accessed ...

What steps should I take to resolve issues with importing Angular modules?

Success! import { MatInputModule } from '@angular/material/input' import { MatSelectModule } from '@angular/material/select' Having Issues import { MatInputModule, MatSelectModule } from '@angular/material' What could be c ...

Unable to find Angular 6 Universal Application code in the view source

When examining the source of my app's home page, I noticed that the header and footer code is visible but not the body code. The body code is supposed to be contained within a <router-outlet></router-outlet>. However, when I navigate to th ...

Issue with IN operator functionality in TypeORM when used with MongoDB

My goal is to fetch a list of items using an array of IDs by utilizing the following code: import { In } from 'typeorm'; ...findBy({ _id: In(ids) }) The IDs are predefined upon creation: @Entity() export class Foo { @ObjectIdColumn({ generated ...

What is the best way to retrieve specific data based on their unique identifier?

Imagine having a table like this, with the following data: Id , Name , IsBillable 1 One 1 2 two 0 3. three 0 I have stored this data in a variable called masterData using the get method, and I am using it to populate a dropdown me ...

Exploring the potential of AssemblyScript in creating immersive WebXR

I have been exploring three.js and webXR for some time now, and I wanted to incorporate it into assembly script. While I know how to make webXR work in TypeScript, I encounter an error when trying to use it in assembly script with the import statement. Her ...

Designate as a customizable class property

I'm struggling to create a versatile inheritance class for my services. Currently, I have two service classes named Service_A and Service_B that essentially do the same thing. However, Service_A works with Class_A while Service_B works with Class_B. T ...

Utilizing Angular to Handle Multiple Sockets on a Single Client

Is it feasible to achieve this task? If not, kindly guide me in an alternative direction. I am managing a server that has the capability for multiple socket-io connections. The server produces a random number and transmits it to registered sockets. In th ...

Angular 5's external JavaScript library

After thoroughly researching this subject, I find myself still lacking comprehension. An example may be the key to understanding. As a newcomer to Angular, my goal is to create a mathematical application for mobile using Ionic. Despite investing two weeks ...

Challenges arise when attempting to break down an API into separate components rather than consolidating it into a

I've been struggling with this issue for a few days now. Problem Explanation: I am trying to use Axios to fetch data and store it in the state for each individual Pokémon. However, currently all the data is being rendered inside a single component w ...

Is it recommended for TypeScript to automatically resolve the index.ts file as the default module file?

Struggling with getting the module resolution to work in TypeScript. Consider the following file structure: /modulename/index.ts Should it be resolved like this? import * as modulename from "modulename" I can't seem to make it work. However, imp ...

Angular 2 orderByPipe not displaying any results initially

At first, I thought the reason for not displaying anything initially was due to it not being async and returning an empty array. Everything worked fine without the pipe, but the posts weren't shown on startup. After submitting a post, all the posts ap ...

Displaying errors to the user using Angular's HttpClient in an Ionic application

I am currently working on a small project and struggling to grasp certain TypeScript concepts. Specifically, I am trying to pass data from a form to an object and then send it via an HTTP service to an endpoint. The response is displayed in the console, in ...

Angular Reactive Forms - Adding Values Dynamically

I have encountered an issue while working with a reactive form. I am able to append text or files from the form in order to make an http post request successfully. However, I am unsure about how to properly append values like dates, booleans, or arrays. a ...

Error in Template Syntax for External Pug Templates: Component template must have a root element, not just plain text

I've been struggling to make Pug templates work with Vue class-based components using a separate file for the pug template. The documentation suggests that adding this code should do the trick: // webpack.config.js -> module.rules { test: /&bsol ...

Tips for deleting on a numeric cell within ag-grid?

While exploring the functionality of AG-Grid with the example provided at this link [, I am currently experimenting with the numeric editor feature. I found this example on the official AG-Grid website [https://www.ag-grid.com/javascript-grid-cell-editor/ ...

Updating the FormControl value using the ControlValueAccessor

I have developed a directive specifically for case manipulation. The code I created successfully updates the visual value using _Renderer2, but I am facing an issue with formGroup.value. Even though the directive visually changes the value as expected, t ...

Analyzing a Typescript project using SonarQube Scanner on a Mac OS slave in Jenkins: A step-by-step guide

My current task involves examining a TypeScript project on Jenkins using the SonarQube Scanner plugin on a Mac OS slave. Software: Jenkins (version 2.32.1) SonarQube Scanner for Jenkins plug-in (version 2.5) SonarQube Scanner (version 2.8) SSH slave plu ...

Issues encountered while attempting to convert HTML Image and Canvas Tags to PDF within Angular 2

I am currently facing an issue with my code. My requirement is to download HTML content as a PDF file. I have been successful in downloading text elements like the <p> tag, but I am encountering difficulties when trying to download images and canvas ...

Updating a data attribute in Angular 2: A different approach

Currently, I am utilizing ConvertFlow to integrate pre-designed form templates into my project. To specify where the form should appear, I include a div with the unique identifier of the form created within their platform. While this process is straightfor ...