Angular 6 编译失败

Angular 6 Failed to compile

示例:Tthis 是应用程序组件的子组件,使用命令行

ng g c emp

创建它。曾经创建的它会在编译时失败 时间。

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

    @Component({
    selector: 'app-emp',
    templateUrl: `
          <h2>EmpList</h2>
          <ul *ngFor="let emp of empArr">
              <li>{{emp.name}} {{emp.id}} {{emp.age}}</li>
          </ul>
          `,
     styleUrls: ['']
    })
    export class EmpComponent implements OnInit {
    public empArr=[
         {"id":1,"name":"jamal","age":25},
         {"id":2,"name":"yasser","age":80},
         {"id":3,"name":"zolla","age":11}
    ];

    constructor() { }

    ngOnInit() {
    }

    }

我收到以下错误消息:

> Module not found: Error: Can't resolve './
>           <h2>EmpList</h2>
>           <ul *ngFor="let emp of empArr">
>               <li>{{emp.name}} {{emp.id}} {{emp.age}}</li>
>           </ul>
>           ' in 'D:\Angular\bind\src\app\emp'
>     ERROR in ./src/app/emp/emp.component.ts
>     Module not found: Error: Can't resolve './' in 'D:\Angular\bind\src\app\emp'

由于您提供的是内联模板,因此组件装饰器中的 templateUrl 属性 应该改为 template

或者,将您的模板放在一个单独的文件中,然后您可以通过URL引用它。

您需要在 emp.component.ts 文件中进行更改。

Angular 6 提供2种方式的模板注入

  1. 通过使用 templateUrl : 如果您使用 templateUrl,您的代码应该如下所示:-

@Component({ selector: 'app-emp', templateUrl: './emp.component.html', styleUrls: [''] })

这里您需要提供 link 外部 html 文件,您可以在其中放置您的 html 代码。 我为此示例创建了 demo

  1. 通过使用模板:如果你只在代码中使用模板,它应该看起来像-

    @组件({ 选择器:'app-emp', 模板: <h2>EmpList</h2> <ul *ngFor="let emp of empArr"> <li>{{emp.name}} {{emp.id}} {{emp.age}}</li> </ul> , 样式网址:[''] })

请使用模板选择器寻找另一个 demo

我认为它会清楚 templateUrltemplate 之间的想法和区别。

您正在向 templateUrl 中提供 html ...

基本上来自 @component 构造函数对象中的 angular2 component.html 链接

  1. templateUrl :这里我们提供 component.html 的相对路径 文件。
  2. template : 这里我们提供 html 在组件中使用。

因此您可以使用任何人并相应地提供输入。