OGZCoder
OGZCoder

Reputation: 285

How can I pass a variable from @Input to a service in an Angular2 component>

So, What I am trying to do seems like it would be trivial. And it probably is. But I can't figure it out. My question is:How can I pass a variable from @Input to a service in an Angular2 component? (Code has been simplified)

My component is as follows:

import { Component, Input } from '@angular/core';
import { CMSService } from '../cms.service';

@Component({
  selector: 'cmstext',
  templateUrl: './cmstext.component.html',
  styleUrls: ['./cmstext.component.css']
})
export class CMSTextComponent {
  constructor(private cms: CMSService) { }

  @Input() id : string;
  content = this.cms.getContent(this.id); // this.id is NULL so content is NULL
}

And then my service:

import { Injectable } from '@angular/core';

@Injectable()
export class CMSService {
    constructor() { }

    getContent(textId:string) : string {
        this.text = textId; // textId is NULL so this.text returns NULL
        return this.text;
    }
}

My component template:

<p>id: {{id}}</p>
<p>Content: {{content}}</p>

When <cmstext id="4"></cmstext> is added to another component template the output is:

id: 4
content:

I'm just diving into Angular2 any help or suggestions would be greatly appreciated!

Upvotes: 4

Views: 4101

Answers (2)

OGZCoder
OGZCoder

Reputation: 285

As pointed out by @Kris Hollenbeck,ngOnInit() was the answer. My final code looked like this. The component now passed the variable to the service.

import { Component, Input, OnInit } from '@angular/core';
import { CMSService } from '../cms.service';

@Component({
  selector: 'cmstext',
  templateUrl: './cmstext.component.html',
  styleUrls: ['./cmstext.component.css']
})
export class CMSTextComponent implements OnInit  {

  public content : string;

  @Input() id : string;

  constructor(private cms: CMSService) { }

  ngOnInit() {
    this.content = this.cms.getContent(this.id);
  }
}

This assigned the data from the service to the variable "content" and the id passed from the element attribute to the variable "id". Both variables were then accessible to the template!

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657741

Just make it a setter and put the code there:

  @Input() 
  set id(value : string) {
    this.content = this.cms.getContent(value);
  }

Upvotes: 3

Related Questions