CounterFlame
CounterFlame

Reputation: 1632

Call function on Component's Input

So I have a Component that looks something like this:

export class TAComponent implements OnInit {
    @Input() postInfo : TracklistPost;
    youtubeUrlOriginal : string;

    ngOnInit() : void {
        this.youtubeUrlOriginal = this.postInfo.getYoutubeUrl();
    }
}

and a class:

export class TracklistPost {
    play_urls       :   PlayUrl[];

    public getYoutubeUrl() : string {
        return this.play_urls[1].value;
    }
}

When I call the getYoutubeUrl() function from the TAComponent, I get an error that this function is not defined. How can something like this be done in Angular2?

Upvotes: 1

Views: 512

Answers (1)

Atal Kishore
Atal Kishore

Reputation: 4738

Create a common service for both the component and add getYoutubeUrl() in the service and use that service in both the components

import { Injectable } from '@angular/core';  
export class CommService {


    play_urls       :   PlayUrl[];
    constructor() {
    }

    public getYoutubeUrl() : string {
        return this.play_urls[1].value;
    }
}

Now Inject this Service at parent of both the component and use this service as shown below

export class TAComponent implements OnInit {
    @Input() postInfo : TracklistPost;
    youtubeUrlOriginal : string;

    constructor( public commService : CommService ) { }

    ngOnInit() : void {
        this.youtubeUrlOriginal = this.commService.getYoutubeUrl();
    }

 }

Upvotes: 2

Related Questions