简体   繁体   English

Angular2 templateUrl加载模板不起作用

[英]Angular2 templateUrl Loading template will not work

I try to load a template in my component via templateUrl. 我尝试通过templateUrl将模板加载到组件中。 But it will not work. 但这是行不通的。 It throws the error in console: error TS2304: Cannot find name 'module' . 它在控制台中引发错误: 错误TS2304:找不到名称“模块” The property moduleId: module.id is set. 设置了属性moduleId:module.id。 When i try to write the template inside the component, it works fine. 当我尝试在组件内部编写模板时,它工作正常。 I use SystemJS. 我使用SystemJS。 The structure looks like: 结构如下:

-app
  |
  |- components
  | |
  | |-projects
  |   |
  |   |-project.component.ts
  |   |-project.component.html
  |
  |-app.component.ts
  |-app.module.ts

project.component.ts project.component.ts

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

@Component({
    selector: 'project',
    moduleId: module.id,
    templateUrl: './project.component.html' 
})

export class ProjectComponent {
    title: string;
    projectName: string;
    projectCity: string;

    constructor () {}

    addProject () {
        console.log('Add project);
    }
}

The very simple html: 非常简单的html:

<div>
    <form novalidate (ngSubmit)="addProject(form.value)" #form="ngForm">

        <div class="form-group">
            <label for="">Projectname</label>
            <input type="text" name="projectName" class="form-control" required [(ngModel)]="projectName">    
        </div>

        <div class="form-group">
             <label for="">Ort</label>
             <input type="text" name="projectCity" class="form-control" required [(ngModel)]="projectCity">    
        </div>

        <button type="submit" [disabled]="!form.valid" class="btn btn-default">Project anlegen</button>

     </form>
</div>

app.component.ts app.component.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ProjectComponent } from './components/projects/project.component';
import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent, ProjectComponent],
    bootstrap: [AppComponent]
})

export class AppModule {}

Have you tried templateUrl: './project.component.html' ? 您是否尝试了templateUrl: './project.component.html' You need to add .html 您需要添加.html

尝试使用此:

template: require('./project.component.html')

Everything is working fine in your code. 一切都在您的代码中正常工作。

Just change your component code as following: 只需更改您的组件代码,如下所示:

From : 

@Component({
 selector: 'project',
 moduleId: module.id,
 templateUrl: './project.component.html' 
})


To : 

@Component({
 selector: 'project',
 moduleId: module.id,
 templateUrl: 'components/projects/project.component.html' 
})

This will definitely work for you. 这绝对适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM