What is causing the issue of undefined values when using a hardcoded string for property binding in a component?

I am currently working with a component named "myComponent" which is essentially a drop down button. I want to utilize this component in two different areas of my project - first in the navigation bar and then in the side nav specifically for mobile view. However, I need to dynamically change the image inside the component based on where it is being displayed, either in the navigation or in the side nav.

Within the myComponent, I am using

@Input() imgName: string = "imageOne"
. In the HTML template of the component, I am interpolating the variable like so
<img ...src="../{imageOne}.png"

The issue arises when I render

<app-my-component [imgName]="imageTwo"></app-my-component>
from the navigation component and find that the value of imgName is undefined. Can anyone provide insight into why this might be happening?

https://i.sstatic.net/m4EPy.png

`export class MyComponent implements OnInit, AfterViewInit {
  @Input() public imgName: string = "img_one";  
  constructor() { }
  ngOnInit() {
    console.log("Inside ng on init");
  }
  ngAfterViewInit(){
    console.log("imgName value is: ${this.imgName}")
  }
}
`

This is how I am rendering my component:

<app-my-component [imgName]="imageTwo"></app-my-component>

Answer №1

The property value of this.imageTwo is being bound, but this property does not actually exist. Therefore, the value is undefined.

Avoid using square brackets when dealing with string constants.

<app-my-component imgName="imageTwo"></app-my-component>
                             ^^^ = should be a string literal

Answer №2

Alongside cgTag's response:

It is advisable to establish your default value within the ngOnChanges lifecycle method as well.

class CustomComponent implements OnInit, AfterViewInit {
  // kept default value in a static property to prevent redundancy
  private static initialImgName: string = "img_one";

  @Input() public imgName: string = CustomComponent.initialImgName;  

  constructor() {
    // once TypeScript is transpiled to JavaScript,
    // the imgName property will be initialized here
  }

  ngOnChanges(values: SimpleChanges) {
    // note that ngOnChanges does not trigger
    // if the component is initiated without any bindings

    // this function runs every time imgName changes,
    // to execute only once, check with values.imgName.isFirstChange()
    if (values.imgName && values.imgName.currentValue === undefined) {
       this.imgName = CustomComponent.initialImgName;
    }
  }

  ngOnInit() {
    console.log("Executing ng on init");
  }

  ngAfterViewInit() {
    console.log(`The value of imgName is: ${this.imgName}`)
  }
}

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 Angular framework is unable to locate a differ that supports the object '[object Object]' which is of type 'object'

In my Angular project, I am calling an API and receiving the following JSON data: { "id": 16, "poste": "ameur taboui", "desciption": "f", "service": "f", ...

Mysterious issue arises during deployment of Typescript-React application on Heroku

I am working on a TypeScript-React application generated using create-react-app. Deploying it to Heroku is proving to be a challenge as the process fails with an error message during installation and build: remote: Creating an optimized production b ...

Is it feasible to replicate an error in TypeScript with certain modifications?

Currently, I'm facing a challenge where I need to utilize Sentry.captureException with an error that I have received. However, before doing so, I am attempting to modify the error message. Despite spending considerable time searching for a solution, I ...

Is a no-cache directive required in Angular index.html?

Is there a way to prevent index.html from caching and instead have it constantly reloaded? I would prefer not to have cache enabled. Any suggestions on how I can achieve this? Thank you! ...

Having trouble with uploading the profile image in Angular 2? The upload process doesn't

I just started learning Angular and decided to create a profile page. But, I encountered an error while trying to upload a profile image. The error message that I received was POST http://localhost:3000/api/v1/users/avatar/jja 500 (Internal Server Error). ...

Angular Material calendar tool customization for designated input

Is it possible to individually control the format of input for a datepicker without affecting the format for the entire module? <input matInput [matDatepicker]="dp" [formControl]="date" [format]="'DD/MM/YYYY'"> <-- Can this be done? < ...

Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller. Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when ...

Creating personalized breakpoints in Material UI using TypeScript

When using the createMuiTheme() function, you have the ability to update breakpoint values like this. const theme = createMuiTheme({ breakpoints: { values: { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920, }, }, }) ...

The Cloudflare KV namespace remains unbound

After running wrangler dev, it appears that Worker KV is not being bound properly: ERROR in /src/handler.ts ./src/handler.ts 16:8-17 [tsl] ERROR in /src/handler.ts(16,9) TS2304: Cannot find name 'generalKV'. This is the content of handler. ...

Navigating user profile routes effectively involves understanding the structure of the application

I'm currently working on developing a user-list feature that will display all users, along with user-detail components for each individual user. My main goal is to restrict access so that only administrators can see the complete list of users, while ...

Choosing the initial object in Angular2 using ngValue

Currently, I am encountering an issue where the initial value is not being set or updated when populating a select element with data from a REST source within my component. To populate the select list, I retrieve the country data as follows: ... ngOnInit ...

Error encountered: ExpressionChangedAfterItHasBeenCheckedError when trying to load the loading indicator

I encountered an issue with my loading indicator that I cannot seem to resolve: LoadingIndicatorComponent.html:2 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'hidden: true&ap ...

Having trouble with the Angular Language Service extension in VS Code for Angular-16?

Upon transitioning to Angular 16, I encountered errors while attempting to edit the components HTML due to the malfunctioning of the Angular Language Service extension. [Info - 09:41:11] Angular language server process ID: 18032 [Info - 09:41:11] Using t ...

Unleashing the Potential of TypeScript Union Types

My code consists of a union type called PromptOptions: type PromptOptions = | BasePromptOptions | BooleanPromptOptions | StringPromptOptions type BasePromptOptions = { kind: string | (() => string) }; type BooleanPromptOptions = { kind: ' ...

I find that the value is consistently undefined whenever I attempt to set it within a promise in Angular

Hi there, I've encountered an issue with my getData() function in accountService.ts. I'm attempting to fetch user data and user account data simultaneously using a zip promise. Although the resolve works correctly and I receive the accurate data, ...

Organizing data with JavaScript: Transforming a flat array into nested JSON structures

In my front-end TypeScript file, there is a list called poMonths: 0: {id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", purchaseMonthString: "Dec-2019" , year: 2019, month: "December"} 1: {id: 2, company ...

Incorporating yarn into your Vue3 project with Typescript

I'm attempting to implement a solution from https://yarnpkg.com/package/vue-disable-autocomplete that disables autocomplete in my Vue3 project. After running yarn add vue-disable-autocomplete, I included the following code: import DisableAutocomplete ...

When the value of a Formcontrol is changed using valueAccessor.writeValue(), it remains unchanged

Encountering a similar issue as seen in this stack overflow post, but the solution provided isn't resolving the issue. Perhaps you can offer assistance on that thread. In my scenario, I have created a directive for formatting phone numbers: import { ...

Incorporating responsive design with React and Typescript

Trying to utilize React with TypeScript, I aim to dynamically generate components based on a field name // Storing all available components const components = { ComponentA, ComponentB, }; // Dynamically render the component based on fieldName const di ...

Is there a way in TypeScript to prevent the modification of a class property and still trigger a runtime error if attempted?

I currently have the following code snippet: class Computed<Value> { _value: Value; get value(){ return this._value; } } When attempting to set the value property, TypeScript returns an error message: Cannot assign to value because it is ...