繁体   English   中英

Angular2 - 无法绑定到“客户”,因为它不是“我的客户”的已知属性

[英]Angular2 - Can't bind to 'customer' since it isn't a known property of 'my-customer'

我正在关注过时的 John Papa 和 Buddy Ward 教程,无法解决这个问题。 我浏览了一堆 SO 帖子,这些帖子导致我没有在我的组件中使用directives:而是在主模块中使用declarations:属性。 仍然没有运气:(下面是控制台错误和它所指的代码。有人可以帮忙吗?谢谢!

客户.component.ts

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

@Component({
    selector: 'app-customer',
    templateUrl: 'app/customer/customer.component.html'
})

export class CustomerComponent implements OnInit {
    @Input() customer: {id: number, name: string};

    constructor() { }

    ngOnInit() { }
}

客户.component.html

<span [style.color]="deansColor">{{customer.id}}</span>
        &nbsp;
<span>{{customer.name}}</span>

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { AppComponent }  from './app.component';
import { CustomerComponent } from "./customer/customer.component";

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, CustomerComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { CustomerComponent } from './customer/customer.component';

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.component.html'
})
export class AppComponent  { 

  title = "Welcome to Dean's World of Angular..."; 
  heading = 'Enjoy your stay!'
  deansColor = 'red';
  customers = [
    {id: 1, name: "Dean"},
    {id: 2, name: "Daryl"},
    {id: 3, name: "Lee"},
    {id: 4, name: "Josh"},
    {id: 5, name: "Gerald"},
  ];

  changeHeadingColor() {
    this.deansColor = this.deansColor === 'blue' ? 'red' : 'blue';
      }

}

应用程序组件.html

<h1>{{title}}</h1>

<!--property binding-->
<div [style.color]="deansColor">
    {{heading}}
</div>

<!--event binding-->
<button (click)="changeHeadingColor()"> 
    Change Heading Color
</button>

<!--two way data-binding (approach #1)-->
<input type="text" [value]="heading" (keyup.enter)="heading = $event.target.value"> 

<!--two way data-binding (approach #1)-->
<input type="text" [(ngModel)]="heading">

<br/>

<ul>
    <li *ngFor="let c of customers">     
        <my-customer [customer]="c"></my-customer>   
    </li>
</ul>

错误

Unhandled Promise rejection: Template parse errors:
Can't bind to 'customer' since it isn't a known property of 'my-customer'.

您使用了错误的选择器。

尝试:

<app-customer [customer]="c"></app-customer>

selector: 'app-customer'更改为selector: 'my-customer' PS 我认为<span [style.color]="deansColor">...</span>应该改变颜色,因为 deansColor 仅在父组件中定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM