In Angular 5, the template is populated with data once it has been bound

Upon manipulating the data, I noticed that the response in the console looks like this:

[{"date":"02-01-2018 - 31-12-2018"},{"date":"01-07-2018 - 31-12-2018"}]

However, when attempting to display this value in a drop down, nothing is shown. It appears that data binding is taking place before the data loading. Can someone please assist?

Below is the code snippet:

Change(opened: boolean) {
    if (opened) { }     
    var rvaldata:any= [];

    calculateRange(this.choosenSub);
    if(rvaldata!='')
    {
    this.nrvaldata=JSON.stringify(rvaldata);
    console.log(this.nrvaldata);
    }
    function calculateRange(_data){
    var r = "";
    for(var i=0;i<_data.length;i++){
       var isArray = Array.isArray(_data[i]);
       if(isArray){
        r+=calculateRange(_data[i]);
       }else{
        var x = _data[i].date;
        r = rvaldata.push({'date':x})
        }
      }
      return JSON.stringify(r);
      }  
}

Here is the HTML code snippet:

<div  class="d-inline-block">
<span class="plabel">Date<span class="star">*</span></span>
<mat-form-field>
<mat-select placeholder="Validity" class="project-tab" [formControl]="toppings" multiple required>
<ng-template >
<mat-option *ngFor="let t of nrvaldata; let i = index" [value]="t.date">{{t.date}}</mat-option>
</ng-template>
</mat-select>
</mat-form-field>
</div>

Your help will be greatly appreciated.

Answer №1

Your code has a problem with the <ng-template> directive. ng-templates are similar to functions in that they are not executed unless called. In other words, they will only be displayed if you use *ngIf="true" or if you use them as a template for another container using an expression.

To fix this issue, remove the ng-template surrounding the mat-option element.

<div  class="d-inline-block">
<span class="plabel">Date<span class="star">*</span></span>
<mat-form-field>
<mat-select placeholder="Validity" class="project-tab" [formControl]="toppings" multiple required>
<mat-option *ngFor="let t of nrvaldata; let i = index" [value]="t.date">{{t.date}}</mat-option>
</mat-select>
</mat-form-field>
</div>

Answer №2

*ngFor requires an array as input, but when you use JSON.stringify, you are providing it with a string instead. You may notice an error in the browser console related to this issue.

To fix this, simply replace

this.nrvaldata=JSON.stringify(rvaldata);

with

this.nrvaldata=rvaldata;

Additionally, remove the ng-template tags and your code should start working as expected.

Check out this StackBlitz demo for a live example

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 TypeORM connection named "default" could not be located during the creation of the connection in a Jest globalSetup environment

I've encountered a similar issue as the one discussed in #5164 and also in this thread. Here is a sample of working test code: // AccountResolver.test.ts describe('Account entity', () => { it('add account', async () => { ...

Preventing Bootstrap modal from closing when clicking outside of the modal in Angular 4

I'm working with Angular 4 and trying to prevent the model from closing when I click outside of it. Below is the code snippet I am using: <div id="confirmTaskDelete" class="modal fade" [config]=" {backdrop: 'static', keyboard: false}" ro ...

The Firebase EmailPasswordAuthProvider is not a valid type on the Auth object

When working in an Angular2/TypeScript environment, I encountered an error when trying to use the code provided in the Firebase documentation. The error message displayed was "EmailPasswordAuthProvider Does Not Exist on Type Auth". var credential = fireba ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Utilizing Conditional CSS Classes in React Material-UI (MUI) 5

I am in the process of migrating from React material-ui 4 to MUI 5. How can I implement this particular design pattern using the new styled API (or any other suitable method)? My project is written in Typescript. const useStyles = makeStyles(theme => ...

Angular navigation bar dropdown menu is not displaying properly

Check out this Bootstrap Navbar I recently added the same code to my Angular project, but I'm having trouble getting the dropdown to display properly. Take a look at the Stackblitz Demo I need help with two things: Getting the dropdown to show c ...

Struggling to identify the origin of a TypeError while running ng test

While running ng test in my Angular 7.2.1 project, I encountered a type error that seems fixable: Uncaught TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. thrown The i ...

Can you provide an overview of the ternary operator within advanced method signatures in TypeScript?

I'm struggling to understand the method signature provided below: export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; This code snippet was in response to a question on c ...

What is the best way to utilize await in promises instead of using then?

How can I correctly handle the Promise.all() method? I'm experiencing issues with resolving the promise that generates a series of asynchronous requests (simple database queries in supabase-pg SQL). After iterating through the results with a forEach l ...

Utilizing Restler Rest client library as an alternative to Angular/HTTP: A guide for seamless integration

Utilizing the Restler library as a Rest client in an IONIC project to interact with a Node.js API, the aim is to replace the use of AngularJS Http service: This approach was attempted: let options = { headers: {'Authorization':[this.token]}}; ...

Nested array in an object within ag-grid

Hello everyone, I am currently working with an array as one of the column data and I am looking for ways to display it using ag-grid. Can anyone advise me on what my options are? columnDefs = [ { field: 'freLoanId' , checkboxSelection: true, ...

Angular CORS Issue - Troubles with Cross-Origin Requests and XMLHttpRequest

I'm trying to make a call to an API from my backend (node) and the Chrome console is showing this error: Access to XMLHttpRequest at 'http://127.0.0.1:4201/api//listar_clientes_filtrado_admin' from origin 'http://localhost:4200' ...

The onChange event for React input does not trigger when the value remains the same

Script: function SingleInput(props: {value: string; onChanged: (value: string) => void}) { const handleChange = useCallback( (e: React.ChangeEvent<HTMLInputElement>) => { const newValue = e.target.value; cons ...

An error occurred when attempting to access the 'selectedZones' property of an undefined variable that has already been initialized and is not empty

I'm troubleshooting an issue with my component that filters build zones based on selected zones in the ngOnInit lifecycle hook. rfid.component.ts @Component(...) export class RfidComponent implements OnInit { gridApi: GridApi; partList = new Be ...

Utilize Angular 6 to Enhance Open Street Maps by Adding a Custom Marker to the Map

After reading through this article, I have successfully developed an OSM layer component. My next goal is to incorporate a pin or marker for a specific geo-location. Has anyone else achieved this task before? ...

How come I'm seeing an extra addition being added to the string after I override it?

My objective is to call a function in a service from a component that will provide me with a string array. The first time I receive an array, everything seems fine. For example: http://localhost:4200/assets/images/hardwoods/american_white_oak.png However ...

When attempting to retrieve and process a JSON from the internet, I encounter "undefined" errors despite the fact that the data appears correctly in the log

I'm having trouble processing the JSON data received from a server. When I attempt to use .forEach on it, I receive an error stating that the data is undefined even though the console.log shows the correct values. What could be causing this issue? Is ...

Creating a unique object by dynamically incorporating features from another object

I've recently implemented a tree structure in my UI using Material Tree, and it requires creating a new object to represent the tree. The initial object format is as follows: [ { name: 'Fruit', children: [ {name: 'Apple& ...

Updating a property in a JavaScript object using Angular

Working with Angular, I have a dataset: export class AppComponent { data = [ { "area1": { "format": "changethis" } ] I am looking to develop a function that can alter the value of a specific key. For e ...

Guide on declaring numerous principals within an AWS CDK policy document

Currently, I am in the process of working with a cdk script and I have the need to specify multiple principals like so: "Principal": { "AWS": [ "arn:aws:iam::AWS-account-ID:user/user-name-1", "arn:aws:iam::AWS- ...