未定义参考输入未定义 - @Input()在Angular 2中不起作用

问题描述 投票:3回答:2

我是一个新手,试图从ng-book 2(v49)学习Angular2。以下是article.componenets.ts文件的内容:

import { Component, OnInit } from '@angular/core';
import { Article } from './article.model';

@Component({
  selector: 'app-article',
  templateUrl: './article.component.html',
 styleUrls: ['./article.component.css'],
 host: {
 class: 'row'
 }
})
export class ArticleComponent implements OnInit {
  @Input() article: Article;



  voteUp(): boolean {
    this.article.voteUp();
    return false;
  }

  voteDown(): boolean {
    this.article.voteDown();
    return false;
  }

  ngOnInit() {
  }

}

这是angular-cli上的错误:

ERROR in C:/Users/saad/Desktop/books/Angular JS2/angular2Reddit/src/app/article/article.component.ts (13,4): Cannot find name 'Input'.)
webpack: Failed to compile.

Console Error

angular typescript angular2-inputs
2个回答
5
投票

您缺少Input指令的导入,因此将第一行更改为

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

优良作法是让@Input参数具有某些值,否则您最终会在应用程序中的某些位置获得未处理的承诺错误。

为此,它可以在ngOnInit或构造函数中定义

ngOnInit() {
   this.article={
         id: 0
         .....
   };
}

要么

constructor(....) {
   this.article={
         id: 0,
         .....
   };
}

3
投票

如果要使用它,则必须导入Input:

import { Component, OnInit, Input } from '@angular/core';
© www.soinside.com 2019 - 2024. All rights reserved.