Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

angular - @Input() value is always undefined

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...