我对Angular并不陌生,希望此代码能够呈现父级提供的数据(也许Angular8更改了语法)。也许我是新来的。具体的问题是,为什么在父级ngFor循环中具有数据绑定的子级组件无法呈现列表中的数据。
console.logs显示数组。
子组件具有一个呈现的复选框;不显示人员姓名,状态和部门。我遵循了以下确切步骤:https://www.youtube.com/watch?v=FGStS1hD5Y4,这是代码:
parent.component.html:
<div>Json results:</div>
<table>
<tr>
<th></th>
<th>Name</th>
<th>Status</th>
<th>Department</th>
</tr>
<tr>
<td>
<app-people
*ngFor="let person of people"
[personItem]="person"
></app-people>
</td>
</tr>
</table>
<router-outlet></router-outlet>
parent.component.ts:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { PeopleService } from './people.service';
import { People } from './people';
@Component({
selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {
people = [];
avatars = [];
constructor(private peopleService: PeopleService,private http: HttpClient) {
this.http
.get(`assets/people.json`)
.toPromise()
.then(data => {
console.log(data);
for (let key in data)
if (data.hasOwnProperty(key)) this.people.push(data[key]);
});
this.http
.get(`assets/avatars.json`)
.toPromise()
.then(data => {
console.log(data);
for (let key in data)
if (data.hasOwnProperty(key)) this.avatars.push(data[key]);
});
}
child.component.html:
<div class="people-container">
<input
type="checkbox"
[checked]="person.isSelected"
(change)="complete.emit($event.target.checked)"
/>
<span [ngClass]="{ selected: person.isSelected }" class="person-title">
<table>
<tr>
<ng-container *ngFor="let img of avatars">
<td *ngIf="personItem.id == img.id"><img [src]="img.avatar" /></td>
</ng-container>
<td>{{ personItem.name }}</td>
<td>{{ personItem.status }}</td>
<td>{{ personItem.department }}</td>
</tr>
</table>
</span>
<button (click)="remove.emit(person.id)">X</button>
</div>
child.component.ts:
import {
Component,OnInit,Input,Output,EventEmitter,ChangeDetectionStrategy
} from "@angular/core";
import { People } from "../people";
@Component({
selector: "app-people",templateUrl: "./people.component.html",styleUrls: ["./people.component.css"],changeDetection: ChangeDetectionStrategy.OnPush
})
export class PeopleComponent implements OnInit {
people = [];
avatars = [];
@Input() personItem: People;
@Output() select = new EventEmitter<boolean>();
@Output() remove = new EventEmitter<number>();
constructor() {}
ngOnInit() {}
}
如果还有其他需要,请询问。