gpt4 book ai didi

javascript - 无法在页面上显示变量中的数据

转载 作者:行者123 更新时间:2023-12-01 03:36:46 25 4
gpt4 key购买 nike

我的 html 页面未显示 component.ts 文件中的数据。变量 console.log(array_no1); 保存着对象,我想在表格中的 html 页面上显示其 array_no1["title"] 值。附上console.log图片:

enter image description here

下面是我的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com