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.