我有两个组件StudentsComponent和UnderGradsComponent。在“学生”组件中,我创建了一种方法来获取列表中“本科”学生的姓名。然后,将这个列表发送给本科生。但是,我总是在undergrads组件中得到未定义的列表。
这是我的StudentComponent的代码
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-students",
templateUrl: "./students.component.html",
styleUrls: ["./students.component.css"]
})
export class StudentsComponent implements OnInit {
students = [
{ name: "Marwa", level: "undergrad" },
{ name: "Heba", level: "undergrad" },
{ name: "Amal", level: "postgrad" }
];
public undergradsList = this.undergrads();
constructor() {}
ngOnInit() {
this.undergrads();
console.log(this.undergrads);
}
undergrads() {
var Arrayres = new Array();
for (var i = 0; i < this.students.length; i++) {
if (this.students[i].level === "undergrad") {
Arrayres.push(this.students[i].name);
}
}
console.log(Arrayres);
return Arrayres;
}
}
这是StudentsComponent的html
<app-under-grads *ngIf="undergradsList" [studentList]="undergradsList">
</app-under-grads>
这是UndergradsComponent的代码
import { Component, OnInit, Input } from "@angular/core";
@Component({
selector: "app-under-grads",
templateUrl: "./under-grads.component.html",
styleUrls: ["./under-grads.component.css"]
})
export class UnderGradsComponent implements OnInit {
@Input() public studentList;
constructor() {}
ngOnInit() {
console.log(this.studentList);
}
}
最后这是我的HTML UnderGradsCompoenent的代码
<h2>UnderGrads</h2>
<div>
<ul>
<li *ngFor="let x of studentList">{{ x }}</li>
</ul>
</div>