0

I want to import a simple local json file in my angular 7 project and use the data in my HTML file. Just a simple example. I have attached a json file as data.json. I want to access the data from this json file in app.component.html in place of {{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"
    ]
}
2

1 Answer 1

0
  1. in

tsconfig.json

add into "compilerOptions":

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

yourComponentFile.ts

thereby:

import { yourObject } from './data/yourJSON.json'
  1. and to use

    dataImportedFromMyJson: any[] = yourObject;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.