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

标签 javascript html angular

我的 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/

相关文章:

javascript - 根据货币获取记录

javascript - 当我们使用 JavaScript 隐藏/显示时清除下拉列表和/或文本框内容 当它们被交替选择时

javascript - 更改按钮类型时丢失表单验证

javascript - 保持一个元素固定,并允许其他元素在移动浏览器地址栏向上滚动时折叠时滚动

angular - 不支持异步加载指令模板 UpgradeComponent

angular - 在 Angular 2 中是否需要指定类型和默认值?

javascript - 使用具有特定移动规则的 DFS 生成迷宫

javascript - 如何避免 React fetch API 替换 url

javascript - 输入号码 HTML5 : is there an event which triggers on every step?

angular - 我可以用其他鼠标事件运行@HoSTListner 吗?