@Input() value is always undefined

AngularTypescript

Angular Problem Overview


I have created a user photo component which takes an @Input() value, this value is the userId. If the value is passed in then I retrieve information from Firebase linking to this userId, if it doesn't then I do something else.

My user-photo component

import { Component, OnInit, OnDestroy, Input } from '@angular/core';

@Component({
    selector: 'user-photos',
    templateUrl: './user-photos.component.html',
    styleUrls: ['./user-photos.component.css']
})

export class UserPhotoComponent implements OnInit {

    @Input() userId: string;

    constructor() { 

        console.log('userId is:',this.userId);

    }


    ngOnInit() {


    }

    ngOnDestroy() {

    }
}

As you can see I have declared the userId as @Input(), now on my edit-profile component I have the following:

<user-photos [userId]="TestingInput"></user-photos>

Now the User Photo component gets rendered as I see the h1 tag appearing, however the userId is always undefined ?

No errors are appearing in the developer console, so I'm not entirely sure what I've done wrong.

Angular Solutions


Solution 1 - Angular

It will be initialized in ngOnInit, not the constructor. (Please also review the Angular Life Cycle Hooks documentation.)

ngOnInit() {
  console.log('userId is:',this.userId);
}

Also if you want to pass a literal like a string and use brackets [] you have to pass it as a string by enclosing the value with single ticks.

<user-photos [userId]="'TestingInput'"></user-photos>

The reason for that is the containing expression is evaluated in the context of the containing component so without it it will try to retrieve and pass a property/field named TestingInput which will be undefined (unless you also happen have a field by that name).

Solution 2 - Angular

In my case i had to use *ngIf = "isLoaded" on the parent's template first.

On Parent Component

    <div *ngIf = "isLoaded">
       <app-child-component [dataToChild]="dataFromParent"> </app-child-component>
    </div>

On Child Component

      @Input() dataToChild: any;
        constructor() { }
        ngOnInit(): void {
             console.log(this.dataToChild);
         }

Solution 3 - Angular

If your input comes delayed (e.g. a slow webservice), the value will at first be undefined until the response arrives from the webservice.

In order to debug this, you could use ngOnChanges() hook, which will fire every time, an input value changes:

ngOnChanges() {
  console.log('data', this.data);
}

which will output something like:

data undefined <- OnInit, value did not arrive yet

data here it is! <- value arrives delayed

Solution 4 - Angular

In my case, I was passing in undefined as an input and I was assuming that Angular will treat the case of undefined the same as the default scenario. This assumption was wrong even if it is not clearly outlined in Angular's Component Interaction documentation. Here is the use case scenario:

parent.component.html:

...
[mVal]="undefined"
...

child.component.ts:

...
@input('mVal')
mVal: boolean = true
...

The value of mVal will be undefined and not true as you might have expected.

Angular will make the value true (default case) only if it is not defined on the parent component; otherwise, it will pass-in the value as it is (even if it is undefined).

You can solve this by checking if the value is undefined on OnInit or even in the component's constructor.

Solution 5 - Angular

In case TestingInput is a variable and not value is better add *ngIf="TestingInput"

<user-photos [userId]="TestingInput" *ngIf="TestingInput "></user-photos>

if we are calling some api, the delay of the response may cause to pass an empty value

Solution 6 - Angular

Use single ticks if you want to use a hardcoded string as parameter

<app-mycomponent [inputProperty]="'test'"></app-mycomponent>

Solution 7 - Angular

any of these answers is not working for me, after some research I have found belove solution,

in HTML.

<app-opportunityTable [tableNAme]="'OPPORTUNITY'"></app-opportunityTable>

in child component

@Component( {
    selector: 'app-opportunityTable',
    templateUrl: './opportunityTable.component.html',
    styleUrls: ['./opportunityTable.component.css'],
    inputs: ['tableNAme']
} )

export class opportunityTable implements OnInit {
         ngOnInit() {
        console.log( "this is it" + this.tableNAme )
         }
}

Solution 8 - Angular

Answering your question

> @Input() value is always undefined

The reason you're getting undefined in ngOnInit is because at the point where the component is initialised you haven't actually passed in userId.

<user-photos [userId]="TestingInput"></user-photos>

In order to get @Input value in the OnInit() function you can do something like :

> My user-photo component

import { Component, OnInit, OnDestroy, Input } from '@angular/core';

@Component({
    selector: 'user-photos',
    templateUrl: './user-photos.component.html',
    styleUrls: ['./user-photos.component.css']
})

export class UserPhotoComponent implements OnInit {

    @Input() userId: string;

    constructor() {  }

    ngOnInit() {
     setTimeout(() => {
         console.log('userId is:',this.userId);  // You will get the @Input value
     });
    }

    ngOnDestroy() {

    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCode RatchetView Question on Stackoverflow
Solution 1 - AngularIgorView Answer on Stackoverflow
Solution 2 - AngularDavid NjugunaView Answer on Stackoverflow
Solution 3 - AngularJohannes HinkovView Answer on Stackoverflow
Solution 4 - AngularMenelaos KotsollarisView Answer on Stackoverflow
Solution 5 - AngularAdel BalbisiView Answer on Stackoverflow
Solution 6 - AngularEnricoView Answer on Stackoverflow
Solution 7 - AngularShafeeq MohammedView Answer on Stackoverflow
Solution 8 - AngularVishal HasnaniView Answer on Stackoverflow