Angular 2如何在对象数组中显示数组对象

时间:2018-09-24 05:25:48

标签: node.js angular mongodb

这是我的json文件,

            country_id:String,
            name:String
            scholardetails:[{
                country_id:String,
                scholarshipname:String,
                scholarshiplink:String
            }]
        },{collection:'new_countryMaster'});

在前端,对于* ngFor这样,

 <div *ngFor="let country of countries">
       <p>{{country.name}}<p>
  </div>
<div *ngFor="let item of countries.scholardetails">
       <p>{{item.scholarshipname}}<p>
  </div>

我的打字稿,

countries: any;

  constructor(private route: ActivatedRoute, private http: HttpClient) { }

  ngOnInit() {
    this.getscholardetails(this.route.snapshot.params['id']);
  }

  getscholardetails(id) {
    this.http.get('http://localhost:3000/api/scholardetails/'+id).subscribe(data => {
      this.countries= data;
    });
  }

我只能获取并显示姓名,而无法获取Scholardetails country_id,奖学金名称和奖学金名称。我找不到我犯错的地方。如果有人知道,请帮助我。

3 个答案:

答案 0 :(得分:1)

country中的*ngFor变量只能在其相应的div标记内访问,因此您的前端HTML必须像这样:

<div *ngFor="let country of countries">
   <p>{{country.name}}<p>

   <div *ngFor="let item of country.scholardetails">
      <p>{{item.scholarshipname}}<p>
   </div>

 </div>

答案 1 :(得分:0)

您需要将第二个ngFor放在第一个ngFor中,并嵌套一个ngFor

<div *ngFor="let country of countries"> <p>{{country.name}}<p>
    <div *ngFor="let item of countries.scholardetails">     
<p>{{item.scholarshipname}}<p>
 </div>
</div> 

答案 2 :(得分:0)

尝试一下,第二个ng应该是这样的。

<div *ngFor="let item of countries['scholardetails']"> {{item.scholarshipname}}
</div>