I'm fairly new to Angular 2, and I'm trying to find the best way to pass data to a nested component, call a method (REST API) using that data, and return the result into the parent HTML.
I understand how to pass the data - just use the @Input decorator on a variable in the child component. That gets the data in. Now I want to process that data and compute a result. I can't do that in the constructor of the child component, because in the constructor, the input value has not yet been passed. So where do I do it? Is there a render event I can use? I arrived at a solution that seems to work very well, I just don't know if I'm breaking some rules or causing issues.
Since I'm using Typescript, I can use setters. I defined a setter for the input value, so in the setter I can run code to process the data. Here is my working code:
import { Component, Input } from "@angular/core";
import { Http } from "@angular/http";
import { AppService } from "./../../services/appservice";
import { UserProfileService } from "./../../services/userprofileservice";
@Component({
selector: "displayname",
template: "{{displayName}}",
providers: [AppService, UserProfileService]
})
export class DisplayName {
public displayName: string;
private profiler: UserProfileService;
constructor(private appService: AppService) {
this.profiler = new UserProfileService(this.appService);
}
@Input("login")
set login(newLogin: string) {
this.profiler.getUserProfile(newLogin, (profile) => {
this.displayName = profile ? profile.displayName : newLogin;
});
}
}
What this code does is take a login name as input, fetch the user's display name, and set the displayName variable to the result. If the result is null, it just returns the login name. Using the @Input decorator on the setter works great, I've just never seen it done before in any examples so I don't know if there is a better way.
My HTML code looks like this (simplified for this example):
<tr *ngFor="let user of userList>
<td><displayname [login]="user.loginName"></displayname></td>
</tr>
Another way to ask this question is to back up to my basic use case, which I think must be very common. How do you dynamically insert data from a REST API into an HTML page? In this case I want to pass in the login name, and render the Display Name, that is fetched from a REST API. In this case I don't need any HTML formatting (you can see my template is just a variable, no HTML) - is there a simpler way to do this? Should I be using an @Output?
Thanks, Randy
OnInit()
. Use constructor just to declare dependencies andngOnInit()
to do initialization for your components...