The @Input property in the template is not successfully assigning a value to the input variable in Angular 5

Exploring some Angular 5 experiments with PrimeNG, I encountered challenges related to Angular 5. After creating a component with the following template:

<p>Chemi-table works! And now, a message from our sponsors: {{this.nombre}}</p>
<p-dataTable [value]="_postsArray" [loading]="loading"
   loadingIcon="fa-spinner" [rows]="10" [paginator]="true" 
   [multiSortMeta]="multiSortMeta" selectionMode="Single" [(selection)]="selectedUserInfo">
    <p-header>Header of Chemi Table.</p-header>
    <p-footer>The bottom part of the chemi table, showing what's being dragged along.</p-footer>
    <p-column selectionMode="single"></p-column>
    <p-column field="userId" header="User ID" sortable="true" [filter]="true" filterPlaceholder="Search"></p-column>
    <p-column field="id" header="IDE" sortable="true" [filter]="true" [filter]="true" filterPlaceholder="Search"></p-column>
    <p-column field="title" header="Title" sortable="true" [filter]="true" filterMatchMode="contains"></p-column>
    <p-column field="body" header="Body" sortable="true" [filter]="true" filterMatchMode="contains"></p-column>
</p-dataTable>

However, the line:

<p>Chemi-table works! And now a message: {{this.nombre}}</p>

does not display anything for {{this.nombre}}, and when debugging in the component, the value is undefined.

The index HTML code is as follows:

<chemi-table [nombre]="Hello World">
Loading chemi's table  </chemi-table>

Here is the corresponding component.ts file:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { UserService } from './shared/user/user.service';
import { IPosts } from './shared/interfaces';
import { DataTableModule, SharedModule } from 'primeng/primeng';
import { HttpClientModule } from '@angular/common/http';

@Component({
  selector: 'chemi-table',
  templateUrl: './chemi-table.component.html',
  providers: [UserService],
  styleUrls: ['./chemi-table.component.css']
})

export class ChemiTableComponent implements OnInit {
  _postsArray: IPosts[];
  msgs : CustomMessage[];
  selectedUserInfo : IPosts;
  @Input() nombre: string;
  constructor(private apiSerivce: UserService) {
    console.log("Constructor chemi table component.");

  }
  getPosts(): void {
    this.apiSerivce.getPosts()
    .subscribe(
      resultArray => this._postsArray = resultArray,
      error => console.log('Error :: ' + error)
    )
  }
  ngOnInit(): void {
    console.log(this.nombre);
    this.getPosts();
  }
}
class CustomMessage{
  severity:string;
  summary:string;
  detail:string;
  constructor(private severity_a: string, private summary_a: string, detail_a:string) {
    this.severity = severity_a;
    this.summary = summary_a;
    this.detail = detail_a;
  }
}

Lastly, here is the module.ts configuration used:

import { HttpModule } from '@http';//for promises, subscribe, etc.
import { BrowserModule } from '@angular/platform-browser';//necessary for rendering on screen
import { NgModule } from '@angular/core';
import { CommonModule } from '@common';
import { Routes, RouterModule } from '@router';//required for redirections
import { UserService } from './shared/user/user.service';//service fetching data
import { IPosts } from './shared/interfaces';//data types
import { MessageService } from 'primeng/components/common/messageservice';//not used
import { DataTableModule, SharedModule } from 'primeng/primeng';//necessary for the table
import { ChemiTableComponent } from './chemi-table.component';//my component

export const ROUTES: Routes = [
  { path: '', component: ChemiTableComponent }//directing a module to a component at a specific route
];
@NgModule({
  declarations: [ ChemiTableComponent ],
  imports: [
    BrowserModule,
    CommonModule,
    DataTableModule,
    SharedModule,
    RouterModule.forChild(ROUTES),
    HttpModule
  ],
  providers: [ UserService ],
  bootstrap: [ ChemiTableComponent ]
})
export class ChemisModule {
 public nombre : string;
 }

Everything compiles smoothly, and the p-datatable functions properly, but I'm unable to make the {{nombre}} variable appear. There seems to be a minor issue that I can't quite figure out.

Answer №1

Your code has a few errors that need to be corrected.

  1. Avoid using this to access your variable in the template. Use {{nombre}} in your markup instead.
  2. No need for public nombre : string; declaration in your ChemisModule.
  3. When passing an object through props, use either
    <chemi-tabla [nombre]="'Hello World'">
    or
    <chemi-tabla nombre="Hello World">
    . If using brackets [], enclose the object with quotes.

Edit

You seem to be attempting to pass an attribute to your bootstrapped component. Refer to this question for more information.

According to the provided link, you cannot pass an Input to your root component. It's likely unnecessary as well. Simply define it within your root component instead.

Answer №2

A close friend of mine, Bunyamin Coskuner, quickly pointed out in his response before mine that the issue stemmed from my component being bootstrapped. The question he referenced above contains the solution I needed. In my component.ts file, I made the following changes:

import { Component, OnInit, Input, Output, EventEmitter, ElementRef  } from '@angular/core';

....

constructor(private apiSerivce: UserService, private elementRef:ElementRef) {
    console.log("Constructor for chemi tabla component.");    
    let nombreAttribute = this.elementRef.nativeElement.getAttribute('nombre');
    this.nombre = nombreAttribute;
    console.log(this.nombre);
  }

With these adjustments, the component now functions correctly. In my posted question, I detail the modifications required.

To access the value of the 'nombre' attribute, I utilized the ElementRef module (from @angular/core) like so: this.elementRef.nativeElement.getAttribute('nombre');, within the constructor "constructor(private apiSerivce: UserService, private elementRef:ElementRef)". This method allowed me to retrieve the property values effectively.

It appears that due to it being a bootstrapped module, further learning is necessary on my part. However, for today, this was the resolution I sought.

I extend my vote to Bunyamin Coskuner for his insightful assistance.

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

The statement 'typeof import("...")' fails to meet the requirement of 'IEntry' constraint

When trying to run npm run build for my NextJS 13 app, I encountered the following type error: Type error: Type 'typeof import("E:/myapp/app/login/page")' does not satisfy the constraint 'IEntry'. Types of property 'def ...

Utilizing Firebase Cloud Functions to perform querying operations on a collection

Imagine having two main collections: one for users and another for stories. Whenever a user document is updated (specifically the values username or photoUrl), you want to mirror those changes on corresponding documents in the story collection. A sample u ...

I need assistance with using the angular-oauth2-oidc library to retrieve data from an asynchronous storage provider and then pass it to a synchronous storage implementation

Typically, the angular-oauth2-oidc library saves tokens in session storage by default. While you can provide your own storage provider through the OAuthStorage class, it requires a storage provider that can retrieve data synchronously. I am developing a ...

Storing an image in MongoDB using Multer as a file from Angular is not working as anticipated

I'm currently dealing with an issue that I believe is not functioning correctly. I installed a library in Angular called cropper.js from https://github.com/matheusdavidson/angular-cropperjs. The frontend code provided by the developer utilizes this li ...

Setting multiple route parameters for a single segment

Let's jump right into the problem at hand. Is there a way to define multiple route parameters for one segment as shown in the route below: The Routes: { path: 'planlist/:departure_:destination/:date', component: ReservationComponen ...

Limit the category to a specific subset of strings

Looking for a way to implement literal type restrictions without using type aliases: const foo = (a: 'string', b: 'string') => { } foo("123", "abc") // should fail foo("123" as 'string', "abc" as 'string') I pr ...

Error: The code encounters a SyntaxError due to an unexpected token '?' in iOS 14

Currently in the process of developing a Headless Shopify project using this starter: https://github.com/vercel/commerce. While testing the demo environment, I encountered some bugs that seem to be specific to iOS 14 or newer. The primary issue stems from ...

What is the best way to retrieve the final value stored?

This is how I am using my Selector:- private loadTree() { this.loading = true; this.store.select(transitionListSelector).pipe().subscribe(data => { console.log(data); data.map(item => { console.log(item); this.tr ...

Looking to programmatically define the locale for Kendo-Ui-Datepicker element

We have integrated a locale service into our existing Angular application, which sets the locale based on a dropdown selection. This locale service is part of the angular-l10n library. After acquiring Kendo-UI for Angular, we were hoping to connect the da ...

Accessing properties in TypeScript using an index that is determined by another property within the same interface

Allow me to illustrate my query with an example rather than simply using words: interface Y { x: number, y: string } interface PairValue<T> { key: keyof T, value: T[this['key']] } const pairValue: PairValue<Y> = { ...

Passing HttpClient from app.module to another module and then to a service in Angular

Currently, I am in the process of developing my own Angular NPM Package with the prefix "ngx-*". I have successfully compiled the package and am now integrating it into a new project by utilizing the npm link command. Within the service, there is a constr ...

There seems to be a lack of information appearing on the table

I decided to challenge myself by creating a simple test project to dive into Angular concepts such as CRUD functions, utilizing ngFor, and understanding HttpClient methods (specifically get and post). After creating a Firebase database with an API key and ...

What is the relationship between an odd number and the value 1 in JavaScript that results in a 'true' outcome?

I encountered a straightforward problem, but the solution has left me perplexed. function transformArray(numbers) { // If 'i' is an odd number, i & 1 will evaluate to 1 or true return numbers.map(i => (i & 1) ? i * 3 : i * 2); } co ...

Encountered an issue finding element with Protractor - Error: script timed out after 20 seconds without receiving a response

I recently created a basic website using Angular 6 and I am facing some challenges while writing e2e tests for it. The first script is causing a lot of trouble for me as it throws the following error: C:\Users\user\Documents\workspace- ...

Retrieve information using Observables just once in Angular 2

One of my Angular 2 components relies on a service that fetches customer data from a Web API and returns an Observable: getCustomers() { return this.http .get(this.baseURI + this.url) .map((r: Response) => { let a = r.jso ...

Difficulty recognizing left click on onmouseup and onmousedown events in React with TypeScript

I am experiencing an issue with my code that is meant to update the mousePressed variable accordingly when the mouse button is pressed and released. Surprisingly, it works as expected for right-click and middle-click events but not for left-click. The ev ...

Encountered an error while trying to update information in Angular

I have been working on a project involving a .NET Core Web API and Angular 11 (Full-Stack) project. I have successfully managed to add data to the database in my back-end, but I am encountering an issue when trying to update the data. Below is a snippet o ...

Submitting JSONL String to a REST API using Angular: A Guide for Sending Data as a File via POST Method

I am currently developing an Angular App that integrates with OPENAI APIs, specifically focusing on their Upload function. The API Endpoint for this function is named "files" and you can find detailed documentation here When testing the request using Pos ...

Can you provide guidance on effectively utilizing a Pinia store with Vue3, Pinia, and Typescript?

I'm currently facing challenges while using the Pinia store with TypeScript and implementing the store within a basic app.vue Vuejs3 option api. Here is my app.js file: import {createApp} from 'vue' import {createPinia} from "pinia&quo ...

Error encountered when transitioning to TypeScript: Unable to resolve '@/styles/globals.css'

While experimenting with the boilerplate template, I encountered an unusual issue when attempting to use TypeScript with the default NextJS configuration. The problem arose when changing the file extension from .js to .tsx / .tsx. Various versions of NextJ ...