[英]Why does the OnInit lifecyclehook not work?
Why doesn't this work??为什么这不起作用? The console keeps giving me a type error;
控制台不断给我一个类型错误; It can't read property sort.
它无法读取属性排序。 Can anyone help me?
谁能帮我? '''
'''
import { Component, OnInit, Input } from '@angular/core';
import { Order } from 'src/app/models/order';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
@Input() orders: Order[];
sortedOrders: Order[];
constructor() { }
ngOnInit(): void {
this.sortedOrders = this.sortOrders(this.orders);
console.log(this.sortedOrders);
}
sortOrders(orders: Order[]): Order[] {
return orders.sort((a, b) => a.personName.localeCompare(b.personName));
}
}
You need to use ngAfterViewInit
lifecycle hook as it is called after Angular has fully initialized a component's view您需要使用
ngAfterViewInit
生命周期钩子,因为它是在 Angular 完全初始化组件视图之后调用的
Try like this:试试这样:
ngAfterViewInit(): void {
this.sortedOrders = this.sortOrders(this.orders);
console.log(this.sortedOrders);
}
You're using @Input()
, so OnInit
your data will not be available, so you should be doing it in OnChanges
您正在使用
@Input()
,因此OnInit
您的数据将不可用,因此您应该在OnChanges
中进行
ngOnChanges(): void {
this.sortedOrders = this.sortOrders(this.orders);
console.log(this.sortedOrders);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.