@Input()值始终未定义 [英] @Input() value is always undefined
问题描述
我创建了一个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屋!