我想在我的angular 7项目中导入一个简单的本地json文件,并使用我的HTML文件中的数据。只是一个简单的例子。我已将一个json文件附加为 data.json 。我想访问 app.component.html 中的json文件中的数据,以代替 {{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"
]
}
答案 0 :(得分:0)
tsconfig.json
添加到“ compilerOptions”中:
"compilerOptions":
{
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
yourComponentFile.ts
因此:
import { yourObject } from './data/yourJSON.json'
并使用
dataImportedFromMyJson:任何[] = yourObject;