@Input()值始终未定义 [英] @Input() value is always undefined

查看:202
本文介绍了@Input()值始终未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个user photo component,它带有一个@Input()值,该值是userId.如果传递了值,那么我将从链接到此userId的Firebase中检索信息,如果没有,那么我会做其他事情.

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.

我的用户照片组件

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() {

    }
}

如您所见,我已经将userId声明为@Input(),现在在我的edit-profile component上,我具有以下内容:

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>

现在,当我看到h1标签出现时,User Photo组件被渲染,但是userId始终是未定义的?

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.

推荐答案

它将在ngOnInit中初始化,而不是在构造函数中初始化. (还请查看 Angular Life Cycle Hooks文档.) >

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>

之所以这样,是因为包含表达式是在包含组件的上下文中求值的,因此,如果没有包含表达式,它将试图检索并传递一个名为TestingInput的属性/字段,该属性/字段将是未定义的(,除非您同样发生有一个名字相同的字段).

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

这篇关于@Input()值始终未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆