我的 html 页面未显示 component.ts
文件中的数据。变量 console.log(array_no1);
保存着对象,我想在表格中的 html 页面上显示其 array_no1["title"]
值。附上console.log
图片:
下面是我的slist.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
declare let $: any;
@Component({
selector: 'app-showlist',
templateUrl: './showlist.component.html',
styleUrls: ['./showlist.component.css']
})
export class ShowlistComponent implements OnInit {
constructor(@Inject(DOCUMENT) private document: any) {}
ngOnInit() {
var keys = Object.keys(localStorage).filter(function(key) {
return /^section\d+$/.test(key);
});
var dataArray = keys.map(function(key) {
return JSON.parse(localStorage.getItem(key));
});
for(var i=0;i<dataArray.length;i++){
var array_no = dataArray[i];
}
var array_no1 = dataArray;
console.log(array_no1);
}
}
我的 slist.component.html
<tr *ngFor="let item of array_no1">
<td>{{item}}</td>
</tr>
基本上我希望标题各占一行。
最佳答案
这是因为 array_no1
是在 ngOnInit() 函数的本地范围内定义的。您需要使用 this
运算符指定 array_no1。
尝试以下
@Component({
selector: 'app-showlist',
templateUrl: './showlist.component.html',
styleUrls: ['./showlist.component.css']
})
export class ShowlistComponent implements OnInit {
constructor(@Inject(DOCUMENT) private document: any) {
this.array_no1 = [] // <= this is important
}
ngOnInit() {
var keys = Object.keys(localStorage).filter(function(key) {
return /^section\d+$/.test(key);
});
var dataArray = keys.map(function(key) {
return JSON.parse(localStorage.getItem(key));
});
this.array_no1 = dataArray;
console.log(this.array_no1);
}
go_to_editsection(index) {
// You cannot access index of the item clicked directly
// Instead you need to pass index specifically, as above
console.log("lets edit");
console.log(this.array_no1[index]);
}
`
}
HTML
<tr *ngFor="let item of array_no1; let i = index">
<td>{{item.title}}
<input id="edit" type="button" name="edit" value="Edit" (click)="go_to_editsection(i)" />
<br> </td>
</tr>
关于javascript - 无法在页面上显示变量中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44215918/