Pass the Data!

Tonight this blog post will be about passing data from a parent to child component with Angular2.

So we will start with a simple component. Let’s use our component from last week

import { Component, OnInit } from '@angular/core';
import { myAppService } './myApp.service';
@Component({
selector: 'my-app',
template: `
<h3>Users</h3>
<div *ngFor="let user of users">
<user-stuff> </user-stuff>
</div>
`
})
export Class MyAppComponent implements OnInit {
private users = [];
constructor(
private myAppService: myAppService,
) {}
ngOnInit() {
this.getUsers();
};
getUsers() {
this.myAppService.getUsers()
.subscribe(
data => this.users = data,
error => this.errorMessage = <any>error
);
}
}

Okay so this component makes a call to the myAppService and fills in the users array with the data it gets. But what if we have a child component that needs to use some of the data in that array? We’ll pass it right along. Luckily angular2 makes this fairly simple! Let’s create a simple component that uses the selector user-stuff that we have in out template.

import { Component, Input } from '@angular/core';
@Component({
selector: 'user-stuff',
template: `
<span>
User Stuff!
</span>
  `
})
export class UserStuffComponent {
@Input() user;
constructor() {}
};

Alright so that’s our child component, this component wants to use the user data from our myAppComponent. If we take a look back at our parent template we can pass that data along.

template: `
<h3>Users</h3>
<div *ngFor="let user of users">
<user-stuff [user]="user"> </user-stuff>
</div>
`

By adding this we have passed the user into our child component which has a user variable and we can now use that however we want. Let’s say our user is an object with a name property and we want to capitalize every letter in that name. We would do that like so.

import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'user-stuff',
template: `
<span>
{{user.name}}
</span>
`
})
export class UserStuffComponent OnInit{
@Input() user;
  ngOnInit() {
this.capUser(this.user);
}
  constructor() {}
  capUser = function (user) {
this.user.name = this.user.name.toUpperCase();
};
};

Here I use ngOnInit to run the function capUser every time this component is initialized. Which should be for every user in our users array in the parent component. Then user.name is inserted into the template and rendered as all caps because of the capUser’s function.

Sure most of the time you wouldn’t want to do this for such a simple case and you could just do it in the parent component but it is a good demonstration of how to pass data down the line. Until next time, thanks for reading.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.