What is the best way to transfer a variable from an @Input property to a service within an Angular2 component?

I'm tackling what seems like a simple task, but I'm struggling to figure it out. My issue is this: How can I successfully pass a variable from @Input to a service in an Angular2 component? (Code has been simplified)

This is my current component setup:

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); // since this.id is NULL, content is also NULL
}

Below is the service being used:

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

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

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

Here's how my component template is set up:

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

When

<cmstext id="4"></cmstext>
is included in another component template, the output looks like this:

id: 4
content:

I'm new to Angular2 and any assistance or recommendations would be greatly appreciated!

Answer №1

To improve efficiency, you can transform it into a setter and incorporate the code within:

  @Input() 
  set reference(id : string) {
    this.content = this.db.retrieveData(id);
  }

Answer №2

Highlighted by @Kris Hollenbeck, the solution came in the form of utilizing ngOnInit(). After implementing this approach, my final code took shape like so. The component successfully transmitted the variable to the corresponding 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 set up facilitated the transfer of data from the service to the designated "content" variable alongside assigning the passed id from the element attribute to the "id" variable. As a result, both variables became easily accessible within the template!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize the power of Angular 12 and Bootstrap 5 with the ability to load multiple imported scss theme files

I'm currently incorporating Angular 12 and Bootstrap 5 into my project. For loading Bootstrap, I have imported it from my SCSS file along with three theme SCSS files. This is how it appears: style.scss: @import './assets/styles/theme1.scss&apo ...

Assign the state to a new object by preserving matching values from the previous state

In my current state, I have an object structured like this: stateObject = {0: 400, 1: 500, 2: 600} Whenever my component rerenders on componentWillUpdate, an additional column is added carrying over the value at key index 0 (400). My goal is to update th ...

What is the best way to streamline a state-dependent getter, with a focus on adhering to SOLID principles?

Is there a more user-friendly way to retrieve different data based on the type in my Angular component? I'm considering separating the component into two: one for phone and one for email. However, I'm concerned about duplicating most of the logi ...

Enable Google Chart to visualize multiple sets of data beyond just 2

This Google chart displays 2 data sets (Tea, Coffee). I've attempted to modify it to show 5 data sets but encountered difficulties. I experimented with changing the button.onclick function and the button value. Below you will find the original code (2 ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

The reason for my inability to include a fresh method in String.prototype using typescript

I attempted to extend the String.prototype with a new method, but I encountered an issue. interface String { newMethod(): void } String.prototype.newMethod = function() {} Although there were no errors in the typescriptlang.org playground, I received ...

Display temporary image until real image loads within ng-repeat angularjs

I am looking to display a placeholder image while the actual image is being loaded. I have tried using the ng-image-appear plugin. The issue I'm facing is that the placeholder image does not appear for img elements inside ng-repeat, although it works ...

"Exploring the World of Angular and Vue: Harnessing the Power

As a beginner developer, I've been busy familiarizing myself with Angular, React, and Vue. It seems like each of these frameworks use "declarative binding" and "templating". While I grasp the concept of what these are, I'm struggling to see why t ...

The command '.' is unable to be executed as an internal or external command, executable program, or batch file when using npm start -- -e=stag -c=it

After executing the command shown below npm start -- -e=stag -c=it An error is generated: ./scripts/start.js -e=stag -c=it '.' is not recognized as an internal or external command, operable program or batch file. What can be done to resolve th ...

What is the method of displaying a querystring on my Angular view page without relying on a controller?

My experience lies in utilizing AngularJS 1. This excerpt showcases the stateprovider configuration present in my config.js file: JavaScript .state('projects', { abstract: true, url: "/projects", templateUrl: "views/common/master_pa ...

Ways to expand the play and pause buttons and adjust the height of an HTML audio player

It's clear that the PLAY/PAUSE icons are smaller than intended, and the entire player is thinner than desired, making it difficult for some viewers to see. How can I enlarge the entire player? I have read that we do not have access to individual contr ...

Leveraging JavaScript to extract data from a JSON file upon clicking a button

Currently, I am working on a problem where the user enters values into a search box, clicks the search button, and then with the onClick event, the search terms are compared to values in a JSON file. I do not have knowledge of jQuery, so if there is a solu ...

What is the reason for jQuery's inability to recognize ":not(#menu *)" in a selector?

I have created a Javascript-based navigation bar that is triggered by clicks instead of hover for better mobile usability. I have made sure to keep the HTML, CSS, and JavaScript code as simple as possible. To ensure that clicking anywhere outside the menu ...

Mongoose consistently fails to properly save dates

I have created a Mongoose model and included a birthdate field in the following way: birthdate: { type: Date, required: [true, "Please enter a birthdate"], lowercase: true, validate: [isDate, "Please enter a valid birthdate&q ...

Ways to send distinct values to updateMany $set in mongodb

I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user. Below is the code snippet that I am working with: func ...

How to Hide Validation Messages Automatically Using Knockout on Page Load

I have been facing a persistent issue where error messages are displaying onload and I want them to appear only on save. Although I have been successful in many cases and can adjust my code accordingly, this particular bug seems to be causing continuous pr ...

The error message "mapboxgl is not defined" indicates that the mapboxgl variable

I have been encountering the following error message in the console, and despite spending hours trying to troubleshoot it, I have been unsuccessful in resolving the issue. Could someone assist me in fixing this problem? error image I am having difficulty ...

Developing Angular PWAs with a focus on microfrontends

I have set up multiple microfrontends using an "app-shell" type of application for the domain root, with each microfrontend on the first path element. Each app is constructed as a standalone angular application utilizing shared libraries to reuse common co ...

Modify the placeholder HTML once a username has been submitted

In order to maximize efficiency, I have included an input box with a placeholder that reads: <input id="username-search" placeholder="explore another user's work"> Once the username is entered, I want to modify the placeholder text to somethin ...

Ways to display the SearchFilter textbox in an Angular Multiselect Dropdown, even when there are no items loaded

Angular version: 8 ng-multiselect-dropdown version: ^0.2.10 I am facing a situation where the user needs to start typing in the search field to load results dynamically into the dropdown. However, in the ng-multiselect-dropdown component, the search box ...