I pass async data from the parent component to the child component. And the child component must know the length of the data in order to do something.
How the problem is that the child component cannot use the Oninit hook to do the work, because the data is currently unavailable. So how do I do this?
The code of the parent component looks like this:
@Component({ moduleId: module.id, selector: 'parent', template: `<div> <child [items]="items | async"> </div>` }) export class Parent implements OnInit { items: Items[]; constructor( private itemService: ItemService, private router: Router ) { } ngOnInit() { this.itemService.getItemss() .subscribe( items => this.items = items, error => this.errorMessage = <any>error ); } }
And the child component is as follows:
@Component({ moduleId: module.id, selector: 'child', template: `<div> <div *ngFor="let itemChunk of itemChunks"></div> content here </div>` }) export class child implements OnInit{ @Input() items: Items[]; itemChunks: Items[][]; ngOnInit() { this.itemChunks = this.chunk(this.Items); } chunk(items: Items[]) { let result = []; for (var i = 0, len = items.length; i < len; i += 6) {
What is the best practice for this?
angular
Allen zhang
source share