从 Angular 2 升级到 Angular 7,无法绑定 [x],因为它不是 [y] 的 属性

Upgrading from Angular 2 to Angular 7, cannot bind [x] since it isn't a property of [y]

解法: 我忘了在 parent 显示 child 的地方更改 HTML。所有组件的选择器在转换中都发生了变化。我忘记检查了,所以感谢所有指向 HTML!

的人

我正在将一个 Angular 2 项目升级到 Angular 7,我 运行 遇到了一个错误,我无法用 google 的答案解决。

我得到的错误是:

Can't bind to 'xClass' since it isn't a known property of 'yComponent'.
1. If 'yComponent' is an Angular component and it has 'xClass' input, then verify that it is part of this module.

我在 google 上找到了两个答案。一是它只发生在生产构建中,但我还没有在生产构建中工作(据我所知)。 另一种是将组件添加到app模块中的declarations。我已经添加了它并确保它位于列表的顶部(因为我读到声明的顺序也很重要)。

我已经尝试将 class 添加到声明中,但这也会导致编译错误。

如何'import'组件中的class?

这是来自应用程序模块的(相关)代码:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { yComponent } from './song-detail/song-detail.component';

@NgModule({
  declarations: [
    yComponent,
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule
    ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

x类:

export class XClass {
    constructor
    (
        public name: string,
        public search_name: string,
        public source: string,
        public source_type: string,
        public source_name: string,
    )
    {}
}

y分量:

import { Component, Input } from '@angular/core';
import { XClass } from '../model/xClass';

@Component({
  selector: 'app-y-component',
  template: `
  <h2>{{ class.name }}</h2>
  `,
  styleUrls: ['./y-component.css']
})
export class yComponent {

  @Input() class:Class;

}

编辑: 我在这里打错了。我有 @Input() xClass:XClass

您正在尝试输入 xClass,同时声明输入 class

接下来应该使用输入 @Input() propery: interface = initialValue

其中 property 是您稍后将使用的名称,例如 <my-awesome-component [propery]="2"></my-awesome-component>

这意味着它应该与您在 [] 中指定的组件相同,或者在仅传递一个字符串时是独立的。

应该提供接口以避免简单的错误。

initialValue 如果您希望使用默认值自定义 属性,您可以使用。

如果您不需要任何初始值,您可以自由使用 @Input() propery: interface,如果您不关心类型,甚至可以 @Input() propery

在组件中声明@Input 属性 时需要小心。 确保在 HTML 中作为组件选择器输入提供的对象与组件声明中预期的对象相同。

例如:

<my-component [additionalDataInput]="myObjectFromParentComponent"></my-component>

并在组件中:

export class MyComponent {
@Input() additionalDataInput: TypeOfMyObjectFromParentComponent; // has to be same type
@Input() class:Class;

应该是

@Input() xClass:XClass;

或者,如果您不想更改变量名称,可以使用

@Input("xClass") class:Class;