Instead of receiving a class, you will receive an object of type HTMLInputElement

I'm attempting to import a JSON file and display it in HTML, but my 'selection' object is always being converted into an HTMLInputElement instead of my intended class.

Here is the JSON data:

[
{
    "id":0,
    "name":"France",
    "acronym":"FR",
},
{
    "id":1,
    "name":"Italy",
    "acronym":"IT",
},
{
    "id":2,
    "name":"Spain",
    "acronym":"SP",
}]

This is the class structure:

export class Country {
id!:number
name!:string
acronym!:string

constructor(id:number, name:string, acronym:string) {
    this.acronym = acronym
    this.name = name
    this.id = id
}}

This is my TypeScript file:

import { Component } from '@angular/core';
import { Country } from './models/Country';
import countries from '../assets/countries.json'; 

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 selection:Country = countries[0]
 allCountries:Country[] = <Country[]>countries

 constructor() {
 }

 onSelect(id:string) {
  let choice:number = +id[0]
  this.selection = this.allCountries[choice]
}
}

And here is the corresponding HTML:

<main class="content" role="main">
  <select #choice class="form-select" (change)="onSelect(choice.value)">
    <option *ngFor="let c of allCountries" [value]="c.id">{{c.name}}</option>
  </select>

  <h2>{{selection.labels}}</h2>
</main>

When I try to access {{selection.name}}, it is empty and {{selection}} displays as [object HTMLInputElement] in Chrome. Can someone please help me figure out why 'selection' is not correctly assigned as an object of type Country?

Any assistance would be greatly appreciated.

Answer №1

Issue Resolved: It turned out that the variable name 'selection' was causing issues in Angular...

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

Angular 2 partial static routing parameters with customizable features

Can an angular 2 routing configuration include a partial-static parameter? Currently, I am using a classic parameter setup like this: const routes: Routes = [ { path: ':type/fine.html', pathMatch: 'full', redirectTo: &ap ...

Is there a feature in VS Code that can automatically update import paths for JavaScript and TypeScript files when they are renamed or

Are there any extensions available for vscode that can automatically update file paths? For example, if I have the following import statement: import './someDir/somelib' and I rename or move the file somelib, will it update the file path in all ...

In Angular/Typescript, dynamically add a class to a `td` element when it is clicked. Toggle the class on and off

My problem arises when trying to individually control the arrow icons for each column in my COVID-19 data table. By using Angular methods, I aim to show ascending and descending arrows upon sorting but run into the challenge of changing arrows across all c ...

Determining the best method for change detection in Angular 2: Choosing between Observable, EventEmitter, and Dot Rule

Managing change detection in Angular2 can be approached in three different methods that I have observed. Utilizing Observables @Injectable() export class TodosService { todos$: Observable<Array<Todo>>; private _todosObserver: any; ...

Issues arise when utilizing Angular HttpClient params in conjunction with the GET method

Can you help me understand how params work with the get method? I currently have this code snippet: path = 'https://example.com/api'; const params = new HttpParams(); params.append('http', 'angular'); return t ...

The specified property is not found in the type 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; }>'

As I delve into utilizing React along with TypeScript and Material-UI components, I encounter some errors. One such error message pops up like this: The Property 'openToYearSelection' is not found on type 'IntrinsicAttributes & Intr ...

Angular 6 - accepting an HTTP GET request as the app loads

Upon the initial startup of my Angular application, just before its pages are loaded onto the user's browser, I aim to retrieve certain information from the HTTP request that triggered the app's launch. More precisely, I am looking to obtain the ...

How to dynamically apply styling to a mat-tab attribute within an Angular 6 component

In my web application, I am utilizing a mat-tab-group that consists of two tabs - Basic Search and Advanced Search. Given that the advanced search tab includes numerous form fields, I am seeking to dynamically adjust the max-height property of the .mat-tab ...

The readiness status of the mongoose connection is resulting in a TypeError: Unable to access undefined properties (reading 'readyState')

I've been utilizing Mongo Memory Server for my unit tests successfully, but all of a sudden mongoose.connection is returning as undefined. This has left me completely baffled! I would have anticipated readyState to at least be 0. import * as mongoose ...

Using Angular to create a dynamic form with looping inputs that reactively responds to user

I need to implement reactive form validation for a form that has dynamic inputs created through looping data: This is what my form builder setup would be like : constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ ...

I encountered an error while working with Node.js where it stated that `readFileSync` is

In my current web app project, I am utilizing Angular 2, typescript, Node.js, and Visual Studio. The task at hand is to access a file stored in the wwwroot folder. To accomplish this, I have devised the following class: ///<reference path="../../node_m ...

Is it possible for lazy loaded features in Angular 6 to share state between features using ngrx?

Suppose I have a mobile application that utilizes lazy loading and also implements ngrx to manage state. In this setup, each feature has its own state instance with respective reducers, actions, etc. For instance: product-feature product-edit prod ...

Tips on switching between two divs with a click event in an Angular 4 loop

This question is in reference to the discussion on displaying/hiding dynamic div IDs in Angular2 as seen on Stack Overflow. I have created a Plunker showcasing the issue I am encountering. I am trying to toggle btn1 and btn2 individually within four boxes ...

Trouble with Angular 4: One-time binding directive not functioning properly

I am currently working on incorporating a directive for one-time binding in order to ensure that when I use this directive, the one-time binding feature is enabled. For reference, here is an example I created: https://stackblitz.com/edit/angular-bhayzy W ...

What is preventing me from being able to use object spread results in TypeScript casting?

Uniqueness in Question My inquiry was not aimed at identifying the type or class name of an object. Rather, it delved into the concept of "casting" an object to a specific type, which arose from a misconception about TypeScript and its functionality. This ...

Invalid Type Property - Request and Response Express Types

When I try to utilize the Request or Response types in this manner: app.use('*', (req: Request, res: Response, next: NextFunction) => { res.set('Cache-Control', 'no-store'); const requestId: string = req.headers[&a ...

The code written inside the <script> tag seems to be malfunctioning when placed in the component.html file within VScode while working with

I'm facing an issue where the script tag for jQuery included in index.html is not being executed within the component.html. There are no errors detected when inspected. Additionally, I have used another script for a toast message box. <script sr ...

Manipulating the distinct look of the final element in an *ngFor loop

I am trying to enhance the appearance of the last line of controls generated by an iterator by making it disabled and somewhat invisible. Currently, my code is functioning well, as shown below. <div *ngFor="let item of data; let last = last;"> &l ...

Angular: navigate to a different page dynamically without triggering a refresh of the current page

Within my EditUserComponent, I am utilizing a path parameter called id. If the id is invalid, I would like to redirect to either the home page or an error page without having to refresh the entire page. Is there a way to achieve this without updating the ...

Angular2 Interactive Modal Pop Up

Here is an example of a modal in HTML code: <app-modal #modal1> <div class="app-modal-header"> header </div> <div class="app-modal-body"> You c ...