Reputation: 37
Good afternoon!
I'm sorry if I'm unable to get this clear, but here's the problem:
i have a file named "heroes.ts", where I have many objects for a "Hero" class (which is exported from another file), here you can see a fragment of it -->
import { Hero, Villain } from '../hero';
export const HEROES: Hero[] = [
{ id: 78251, name: 'Fareeha Amari', codename: 'Pharah', alive:true },
{ id: 15964, name: 'Gengi Shimada', codename: 'Gengi', alive:true },
{ id: 21345, name: 'Angela Ziegler', codename: 'Mercy', alive:true },
{ id: 84519, name: 'Lena Oxton', codename: 'Tracer', alive:true },
{ id: 64518, name: 'Jeese Mccree', codename: 'Mccree', alive:true },
..............]
these pieces of information are used inside another file, called "heroes.component.html". After a certain point, i need to call this data. And I do it like this (mostly, without any problem):
<h2>Heroes</h2>
<ul id="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<p> ID: {{hero.id}} | {{hero.name}}, codename {{hero.codename}}.
<!-- Until here, everything is AOK and printed -->
Status: <script> aliveDead() </script> </p>
<!-- Here lies the preoblem, nothing gets printed after "Status -->
</li>
You must be wondering where is aliveDead(), i have this function in this same file:
<script>
function aliveDead()
{
if( hero.alive == 1 )
{
return "Active";
}
else
{
return "Dead";
}
}
//OBS: i tried using hero.alive and hero as parameters for this function
//it does not work
</script>
I need to make this function run inside the script tags and return me a value that can be printed after the "Status" using, as parameter, the information provided from the first chunck of code ( "heroes.ts" )
Again, i'm sorry if i can't really explain that well, but i did my best
thanks anyway,
chab
Upvotes: 1
Views: 75
Reputation: 191749
Inside your heroes.ts
component where you have hero.id
, etc. you can define aliveDead
instead.
Status: {{aliveDead(hero)}}
If you really want aliveDead
to be defined separately, you can just put it in a separate file. Then you can import it in heroes.ts
:
import { aliveDead } from 'path/to/aliveDead.ts';
@Component(...)
class HeroesList {
...
// Assign your declared function to a component property
aliveDead = aliveDead;
}
Another more efficient way to do this would be to create a pipe:
import { Pipe, PipeTransform } from '@angular/core';
/**
* Pass-through pipe that mocks the `translate` pipe used for L10n for tests
*/
@Pipe({ name: 'aliveDead' })
export class HeroStatusPipe implements PipeTransform {
transform(hero) {
if (hero.status === '1') {
return 'Active';
}
return 'Dead';
}
}
Then you will have to add this pipe to your module declarations. In your template you will be able to use Status: {{hero | aliveDead}}
Upvotes: 1