无法加载Angular2子组件

时间:2017-02-12 13:05:51

标签: angular

Product-List Component.ts

import {Component,OnInit} from '@angular/core';
import {IProduct}  from './product';

@Component({
    selector: 'pm-products',
    templateUrl: 'app/products/product-list.component.html',
    styleUrls:['app/products/product-list.component.css']
})

export class ProductListComponent implements OnInit{
    pageTitle:string = 'Product List';
    imageWidth:number = 50;
    imageMargin:number = 2;
    showImage:boolean=false;
    listFilter:string='cart';
    products: IProduct[] = [
        {
        "productId": 1,
        "productName": "Leaf Rake",
        "productCode": "GDN-0011",
        "releaseDate": "March 19, 2016",
        "description": "Leaf rake with 48-inch wooden handle.",
        "price": 19.95,
        "starRating": 3.2,
        "imageUrl": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png"
    },
    {
        "productId": 2,
        "productName": "Garden Cart",
        "productCode": "GDN-0023",
        "releaseDate": "March 18, 2016",
        "description": "15 gallon capacity rolling garden cart",
        "price": 32.99,
        "starRating": 4.2,
        "imageUrl": "http://openclipart.org/image/300px/svg_to_png/58471/garden_cart.png"
    }
    ];

    toggleImage():void{
        this.showImage = !this.showImage;
    }

    ngOnInit():void{
        console.log('In OnInit');
    }
}

我的产品-List.component.html

<ai-star>/ai-star>

嵌套组件

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

@Component({
    selector: 'ai-star',
    templateUrl:'app/shared/start.component.html',
    styleUrls:['app/shared/star.component.css']
})

export class StarComponent implements OnChanges{
    rating : number=4;
    starWidth : number;

    ngOnChanges():void {
        this.starWidth =  this.rating * 86/5;
    }
}

我的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 {ProductListComponent} from '../products/product-list.component';
import {StarComponent} from '../shared/star.component';


@NgModule({
  imports: [ BrowserModule,FormsModule ],
  declarations: [ AppComponent,
                  ProductListComponent,
                  StarComponent
               ],

  bootstrap: [ AppComponent ]
})
export class AppModule { }

当我执行此代码(npm start)时,我收到错误

  

'ai-star'不是已知元素:   1.如果'ai-star'是Angular组件,则验证它是否为此模块的一部分。

如何加载子组件。我正在使用VSCode。

1 个答案:

答案 0 :(得分:0)

我认为你得到的错误就像这些行中的某些内容一样......

If 'ai-star' is a Webcomponent then add "CUSTOM_ELEMENTS_SCHEMA" to the NgModule...

所以你可以尝试这样做 - 在你的NgModule中,像这样添加schemas

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  imports: [...],
  declarations: [...],
  providers: [ ... ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA], // add this!
  bootstrap: [ AppComponent ]
})