Leverage local JSON file data in HTML using TypeScript and Angular 7 for enhanced functionality

I am looking to incorporate a basic local JSON file into my Angular 7 project and utilize the data within my HTML file. Just a straightforward example. The JSON file is named data.json. I aim to retrieve the information from this JSON file in app.component.html instead of using {{item}}

app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('detailsPanel') details;
  @ViewChild('displayDetails') displayDetails;


  // Need to access this data from a JSON file
  title = 'dragNdrop';
  todo = [
    'Get to work',
    'Pick up groceries',
    'Go home',
    'Fall asleep'
  ];

  done = [
    'Get up',
    'Brush teeth',
    'Take a shower',
    'Check e-mail',
    'Walk dog'
  ];

  elementDetails = "";

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
                        event.container.data,
                        event.previousIndex,
                        event.currentIndex);
    }
  }

  showDetails(text){
    this.elementDetails = text;
  }
}

app.component.html

<div class="container-fluid" style="padding: 2%;">
  <div class="row">
    <div class="col-md-3">
      <h2>Drag and Drop</h2>
    </div>
  </div>

  <div class="row">
    <div class="col-md-3" style="border-right: 1px solid black; height: 100%;">
      <div cdkDropList #todoList="cdkDropList" [cdkDropListData]="todo" [cdkDropListConnectedTo]="[doneList]"
        class="example-list" (cdkDropListDropped)="drop($event)">
        <div class="example-box" *ngFor="let item of todo" cdkDrag>{{item}}</div>
      </div>
    </div>

    <div class="col-md-6">
      <div cdkDropList #doneList="cdkDropList" [cdkDropListData]="done" [cdkDropListConnectedTo]="[todoList]"
        class="example-list" (cdkDropListDropped)="drop($event)">
        <p #detailsPanel class="example-box" *ngFor="let item of done" (click)="showDetails(detailsPanel.innerText)" cdkDrag>{{item}}</p>
      </div>
    </div>

data.json

{
    "list1": [
        "A",
        "B",
        "C",
        "D"
    ]
}

Answer №1

  1. inside

tsconfig.json

insert the following code snippet under "compilerOptions":

    "compilerOptions": 
    {
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true
} 
  1. you can now access and import your data from a JSON file in

yourComponentFile.ts

like this:

import { yourObject } from './data/yourJSON.json'
  1. to use the imported data, assign it to a variable like so:

    dataImportedFromMyJson: any[] = yourObject;

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

React - Component not updating after Axios call in separate file

Recently I decided to delve into React while working on some R&D projects. One of my goals was to build an application from scratch as a way to learn and practice with the framework. As I started working on my project, I encountered a rather perplexin ...

Utilize POJO to extract JSON data specifically when the key name consists of numbers

I am attempting to process a unique JSON data using a Wrapper class, which contains keys with numeric values as shown below : { "date":"2018-11-01", "hours":"01-Nov 08:00", "1011":"837.7500", &quo ...

Encountering a SonarQube error message stating "Unnecessary 'undefined' should be removed" when using "undefined" as a function argument

When calling a function, I have been passing "undefined" multiple times as a parameter. However, the SonarQube report is flagging an error stating "Remove this redundant undefined". https://i.stack.imgur.com/YhOZW.png It should be noted that the function ...

How to Filter Arrays in NodeJS without having prior knowledge of the value's position

I'm currently tackling a project that involves scraping websites to generate HTML in JSON format, with the main focus being on identifying and extracting "forms" within these JSONs. I initially attempted to utilize the native array filter function to ...

Switch up the default font in your Nuxt 3 and Vuetify 3 project

I've been doing a lot of searching on Google, but I can't seem to find the solution. It seems like the challenge might be that the Nuxt 3 + Vuetify 3 combination isn't widely used yet? My current task is to implement a custom default font. ...

Clicking on a component in Nuxt will trigger it to open

Is there a way to trigger a modal window to open when a button is clicked without storing the modal window in the header? file header: <template> <section class="header"> <div class="header-container"> ...

Navigating optional fields in a Python dictionary

Working with JSON data in Python dictionaries can be tricky, especially when dealing with optional fields that may contain nested dictionaries. Take for example: dictionary1 = {"required": {"value1": "one", "value2" ...

A guide to efficiently removing an element in Angular using TypeScript by considering certain properties

I need help removing an element from an array based on any property such as its key, name, or email. HTML <tr *ngFor="let person of persons;" (click)="remove(person.key)"> <td>{{person.key}}</td> <td>{{person.name}}</td> ...

Postman's ability to capture elements that meet specific criteria set by another element

Here is the output of my response code: [ { "id": 364, "siteName": "FX21 - PortA", }, { "id": 364, "siteName": "FX21 - PortB", }, { "id": 370, "siteName": "FX05 - ER", }, I'm tr ...

I am interested in duplicating the li elements retrieved from a JSON source

$.getJSON("leftlist.json" , function(data) { $.each(data.articles,function(){ $('#ullist').before("<li id='mylic' style= color:blue class='item new"+cc+"'> "+el.name+"<div class='block'>&l ...

Creating nested JSON using xpath by utilizing SmarGWT's DynamicForm and Form items

I have successfully set up a SmarGWT datasource that retrieves nested JSON data like this: {username:"tom",password:"pwd",userType:{id:1,name:"admin user type"}} The DataSource is configured with the following fields: DataSourceTextField usernameField = ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Boosting a term query in Elastic search by giving it a negative boost

Currently, my queries involve positive boosting of a specific term like this: "query": { "bool" : { "must" : { "term" : { "title" : {value :"word", boost: 2.0}} } } } You can read more ab ...

"Encountering issues with running Mongoimport on Mac due to a variable within the

I am encountering an issue while attempting to import a JSON file into MongoDB. Interestingly, when I use this specific command, the file imports successfully: mongoimport -d reps_development -c users --jsonArray --file ~/reps/scripts/mockUserData.json H ...

Creating a JSON File with an Illustrator Script

Currently, I've been working diligently on developing a system that allows me to export my swatches from Illustrator as a JSON object. This will greatly simplify the process of updating my App. By utilizing the illustrator scripting API, I've suc ...

Should certain data still have its own column even if a json(b) column is present?

While I appreciate general answers, I will also present a more abstracted version of my specific scenario. My Page model utilizes the Ancestry gem to structure itself into a tree for sitemap and navigation purposes. For each page, there will be a jsonb c ...

The process of extracting all arrays from a JSON object

Within my JSON object, there is a list of countries each with multiple regions stored in an array. My goal is to extract and combine all the regions into one single list. However, when I attempt to map the data, it does not consolidate all the regions as e ...

Step-by-step guide on building a wrapper child component for a React navigator

When using the Tab.Navigator component, it is important to note that only the Tab.Screen component can be a direct child component. Is there a way in Typescript to convert or cast the Tab.Screen Type to the TabButton function? const App = () => { retur ...

Error in Typescript: The element is implicitly assigned an 'any' type due to the inability to use a 'string' type expression as an index

I'm a beginner with TypeScript and I encountered an error that's confusing to me while trying to follow an online tutorial on sorting data in Reactjs using React hooks. Here is the section of my component code where the error occurs: Element imp ...

Translate this Python JSON string "column1=value1;column2=value2" into a dictionary format: {"column1":"value1","column2":"value2"}

I have a simple request. I need to change this structure: "column1=value1;column2=value2" to JSON format like this: {"column1":"value1","column2":"value2"} If you know the best way to do this in Python, please share. Thank you in advance. ...