@Input()值始终未定义

Cod*_*het 45 typescript angular

我创建了user photo component一个@Input()取值,这个值是userId.如果传入该值,那么我将从Firebase链接到此userId的信息中检索信息,如果没有,那么我会执行其他操作.

我的用户照片组件

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

    }
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我已经将userId声明为@Input(),现在在我身上edit-profile component我有以下内容:

<user-photos [userId]="TestingInput"></user-photos>
Run Code Online (Sandbox Code Playgroud)

现在,当我看到h1标签出现时,用户照片组件会被呈现,但是userId总是未定义的?

开发人员控制台中没有出现错误,所以我不完全确定我做错了什么.

Igo*_*gor 98

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

ngOnInit() {
  console.log('userId is:',this.userId);
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您想传递像字符串一样的文字并使用括号[],则必须通过用单个刻度括起来将其作为字符串传递.

<user-photos [userId]="'TestingInput'"></user-photos>
Run Code Online (Sandbox Code Playgroud)

原因是包含表达式是在包含组件的上下文中进行评估的,所以如果没有它,它将尝试检索并传递一个TestingInput未定义的属性/字段(除非你的名字也有一个字段).


小智 15

就我而言,我必须首先在父模板上使用 *ngIf = "isLoaded"。

在父组件上

    <div *ngIf = "isLoaded">
       <app-child-component [dataToChild]="dataFromParent"> </app-child-component>
    </div>
Run Code Online (Sandbox Code Playgroud)

在子组件上

      @Input() dataToChild: any;
        constructor() { }
        ngOnInit(): void {
             console.log(this.dataToChild);
         }
Run Code Online (Sandbox Code Playgroud)

  • @user2814648 只是想说一年多后 - 经过 4 个小时的挤压 stackoverflow 你的答案是有效的。太感谢了! (5认同)
  • 我能够使用此代码。`&lt;div *ngIf = "dataFromParent"&gt; &lt;app-child-component [dataToChild]="dataFromParent"&gt; &lt;/app-child-component&gt; &lt;/div&gt;` (4认同)
  • *ng如果确实如此!谢谢兄弟! (2认同)

Joh*_*kov 11

如果您的输入延迟(例如,缓慢的 Web 服务),则该值将首先是未定义的,直到来自 Web 服务的响应到达。

为了调试这个,你可以使用 ngOnChanges() 钩子,它会在每次输入值改变时触发:

ngOnChanges() {
  console.log('data', this.data);
}
Run Code Online (Sandbox Code Playgroud)

这将输出如下内容:

data undefined <- OnInit,值尚未到达

data here it is! <- 值延迟到达


Men*_*ris 8

在我的情况下,我undefined作为输入传入,我假设Angular将处理undefined的情况与默认情况相同.即使Angular的组件交互文档中没有明确概述,这种假设也是错误的.以下是用例场景:

parent.component.html:

...
[mVal]="undefined"
...
Run Code Online (Sandbox Code Playgroud)

child.component.ts:

...
@input('mVal')
mVal: boolean = true
...
Run Code Online (Sandbox Code Playgroud)

价值mVal将是,undefined而不是true你可能预期的.

只有在父组件上没有定义时,Angular才会使值为true(默认情况); 否则,它将按原样传递值(即使它是undefined).

您可以通过检查值是否未定义OnInit或甚至在组件的构造函数中来解决此问题.


小智 5

我花了很多时间来解决这个最愚蠢的@Input 错误。它应该是:

<user-photos
  [userId]="TestingInput">
</user-photos>
Run Code Online (Sandbox Code Playgroud)

并不是

<user-photos>
  [userId]="TestingInput"
</user-photos>
Run Code Online (Sandbox Code Playgroud)

如果有人像我一样犯了语法错误,也许会有帮助