Angular 4: Pass data parent to child component (part 2 of 2)

The full code for part 2 here and demo on gh-pages here.

Following on from part 1, next we will pass an array of objects between components.

In child.component.ts we add another @Input like this,

@Input() data: {name: string, id: number}[] = [];

Then to app.component.ts add,

  id: number = null;
  name: string = null;
  details: {name: string, id: number}[] = [];

Then in app.component.html we will add input forms for ‘id’ and ‘name’.

<label for="box2">id:</label>
<input type="number" name="box2" class="form-control" [(ngModel)]="id" />
<label for="box3">name:</label>
<input type="string" name="box3" class="form-control" [(ngModel)]="name" />
<p><button (click)="pushto()" class="btn btn-warning btn-sm">Submit</button></p>

again we are using [(ngModel)]. We also have a submit button and when this data is submitted the pushto() function is called.

The pushto() function in app.component.ts is,

pushto(){
    this.details.push({name: this.name, id: this.id});
    this.name = null;
    this.id = null;
  }

This will push a new object to the details array. Let’s display them on the root app page in app.component.html

<div class="col-xs-4 col-md-4">
  <p *ngFor="let element of details"><strong>name: </strong>{{element.name}} <strong>id: </strong>{{element.id}}</p>
</div>

Next we want to pass the array ‘details’ to the child component. To do this we include ‘[data]=”details”‘ in the <app-child> tag like this,

<app-child [quantity]="newvalue" [data]="details"></app-child>

So now in the child component child.component.html we will use *ngFor to loop through the array ‘data’.

<p *ngFor="let element of data"><strong>name:</strong> {{element.name}} <strong>id:</strong> {{element.id}}</p>

The full code for part 2 here and demo on gh-pages here.