簡體   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