在Angular中,如果数组中的数据未显示在模板中,可能是由于以下几个原因导致的:
- {{ item }}
import { Component, OnInit } from '@angular/core';
import { DataService } from 'path/to/data.service';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
items: any[];
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getItems().subscribe(items => {
this.items = items;
});
}
}
slice()
方法来创建一个新的副本,从而触发变更检测。addItem(newItem: any) {
this.items.push(newItem);
this.items = this.items.slice();
}
ngOnInit()
生命周期钩子之后。解决方法是将数据初始化移到ngOnInit()
中。export class MyComponent implements OnInit {
items: any[];
constructor(private dataService: DataService) { }
ngOnInit() {
this.items = this.dataService.getItems();
}
}
通过检查以上几个方面,你应该能够解决数组中数据未显示在模板中的问题。