未处理的Promise拒绝:Angular 2上的模板解析错误

时间:2017-04-01 23:42:52

标签: javascript angular

我是角度2的新手,我正在尝试创建一个简单的模块,但是我收到了错误。

app.component.html

import { Component } from '@angular/core';
import { Cronometro } from '../app/modules/cronometro';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  //directives:[Cronometro]
})
export class AppComponent {

}

app.component.html

<h1>
  {{title}}
</h1>
<h2>Cronometro</h2>
<cronometro></cronometro>

cronometro.ts

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

@Component({
  selector: 'cronometro',
  templateUrl: 'app/modules/cronometro.html'
})

export class Cronometro {
  title = 'My First Angular App';

  public horas:number = 0;
  public minutos:number = 0;
  public segundos:number = 0;
  public started = null;

  constructor(){

  }

  start(){
    if(!this.started){
      this.started = true;
      console.log("start");
      this.started = setInterval(
        ()=>{
          this.segundos++;
          if(this.segundos == 60){
            this.minutos++;
            this.segundos = 0;
            if(this.minutos == 60){
              this.minutos = 0;
              this.horas++;
            }
          }
        }
        ,10);
    }
  }

  lapse(){

  }

  stop(){
    console.log("stop");
    clearInterval(this.started);
    this.started = null;
  }
}

cronometro.html

<button (click) = "start()" >Start</button>
<button (click) = "lapse()" >Lapso</button>
<button (click) = "stop()" >Stop</button>
<div >
  <p>{{horas}}:{{minutos}}:{{segundos}}</p>
</div>

这是错误信息

Unhandled Promise rejection: Template parse errors:
'cronometro' is not a known element:
1. If 'cronometro' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
</h1>
<h2>Cronometro</h2>
[ERROR ->]<cronometro></cronometro>
"): ng:///AppModule/AppComponent.html@4:0 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:
'cronometro' is not a known element:
1. If 'cronometro' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
</h1>
<h2>Cronometro</h2>
[ERROR ->]<cronometro></cronometro>
"): ng:///AppModule/AppComponent.html@4:0

我如何将其作为已知元素?

1 个答案:

答案 0 :(得分:1)

您需要将组件添加到NgModule,如错误所示:

  

如果&#39; cronometro&#39;是一个Angular组件,然后验证它是否是该模块的一部分。

app.module.ts中,将其添加到声明数组中:

@NgModule({
  declarations: [AppComponent, Cronometro ],
})
export class AppModule { }

我建议您使用Angular CLI,因为当您使用其命令生成组件/指令/ etc时,它会自动执行此操作。