This component is straight from the angular2 docs.
The only modification I have added is the import of a function from another file into this component:
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { Hero } from './hero';
import { HeroService } from './hero.service';
// IMPORTING HELPER FUNCTION FROM LIB
import {
showOrNot
} from '../helpers';
@Component({
moduleId: module.id,
selector: 'my-hero-detail',
templateUrl: 'hero-detail.component.html'
})
export class HeroDetailComponent implements OnInit {
// USING IMPORTED HELPER FUNCTION FROM LIB
showOrNot: showOrNot;
constructor(
private heroService: HeroService,
private _activatedRoute: ActivatedRoute,
private location: Location
) {}
@Input()
hero: Hero;
goBack(): void {
this.location.back();
}
ngOnInit(): void {
this._activatedRoute.params.forEach((params: Params) => {
let id = +params['id'];
this.heroService.getHero(id)
.then(hero => this.hero = hero);
});
}
}
Then in the template for the component a simple show or not based on the return of the showOrNot function.
<div *ngIf="showOrNot()">
<h1>{{hero.name}} details!</h1>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name"/>
</div>
<button (click)="goBack()">Back</button>
</div>
I can appreciate this code and it's neatness, this above component only uses includes the functions is has been told to and not the whole lot.
But, is there a way to optimize this? To use this code in the template I not only need to import it into the component but also reference it in another class method within the component.
is there a way to call the helper class's method from the template directly without having to route it through yet another function?
You can make a helperService, inject it into the component, and then use it in your template.
constructor(
private heroService: HeroService,
private _activatedRoute: ActivatedRoute,
private location: Location,
private helperService: HelperService,
) {}
<div *ngIf="helperService.someHelperFunction()">
<h1>{{hero.name}} details!</h1>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name"/>
</div>
<button (click)="goBack()">Back</button>
</div>
To better understand it would be nice to know what your function need (inputs) and what it should do.
Service solution is a neat one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With