【问题标题】:Angular 2 directives errorAngular 2 指令错误
【发布时间】:2017-02-02 15:33:45
【问题描述】:

我正在使用最终的 Angular 2 发行版。我已经按照官方网站angular 2 quickstart 中的说明设置了启动文件。在我的 app.component.ts 文件中,我制作了 2 个组件。代码如下:-

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

@Component({
    selector: 'demo',
    template:`
        <h2>Hi, demo !!</h2>
    `
})

export class DemoComponent implements OnInit{
    constructor(){}

    ngOnInit(){

    }
}

@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1> 
    <demo></demo>
    `

})
export class AppComponent implements OnInit{ 
    constructor(){}
    ngOnInit(){

    }
}

my-app 的组件中,我使用了指令选择器,它是一个数组。但是编辑器(VS Code)显示错误。 chrome的控制台抛出错误,告诉 模板解析错误: 'demo' 不是已知元素:

请帮我解决这个问题。谢谢

这是我的 app.module.ts 文件

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';

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

【问题讨论】:

    标签: angular angular2-directives angular2-components


    【解决方案1】:

    您必须在模块的declarations 属性中定义您的组件。

    app.module.ts

    import { AppComponent, DemoComponent  }   from './app.component';
    
    @NgModule({
      imports:      [ BrowserModule ],
      declarations: [ AppComponent, DemoComponent ], <== here
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    

    并将其从AppComponentdirectives 属性中删除。它已被弃用。

    app.component.ts 罢工>

     directives: [DemoComponent] ,
    

    【讨论】:

    • 无论你说什么我都做到了。但它仍然显示错误。 :(
    • 你忘记导入DemoComponent
    • 非常感谢,兄弟。成功了:)
    【解决方案2】:

    directives 已弃用。创建一个NgModule 并将其添加到declarations

    https://angular.io/docs/ts/latest/guide/ngmodule.html

    【讨论】:

    • 我是 Angular 2 的新手。请您详细说明一下。
    • 按照@yurzui 的示例进行快速修复,但如果有机会,请阅读我发布的完整文档。我无法比文档更好地详细说明。
    【解决方案3】:

    您需要在声明数组中声明 DemoComponent 并确保从 AppComponent

    中删除 declaration:[DemoComponent]

    仅供参考:在 @Component({}) 装饰器的指令元数据中声明管道、组件、指令已被删除。该声明不再存在。所以你面临一些问题。您需要在 @NgModule({}) 装饰器中声明管道、指令、组件。

    如果在同一个文件中需要导入为import { AppComponent,DemoComponent} from './app.component';

    import {DemoComponent} from 'valid path';             //<<===here
    OR   
    import {AppComponent, DemoComponent} from './app.component';  //<<===here
    
    
    @NgModule({
      imports:      [ BrowserModule],
      declarations: [ AppComponent,DemoComponent],       //<<<====here
      providers:[],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    

    【讨论】:

    • 如果在同一个文件中需要导入为import { ppComponent,DemoComponent} from './app.component';
    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 2018-01-17
    • 2017-03-25
    • 1970-01-01
    • 2019-11-30
    • 2017-06-27
    • 1970-01-01
    • 2017-08-24
    相关资源
    最近更新 更多