2016-05-15 81 views
4

在阅读与Angular2相关的在线博客时,我遇到以下语法。Angular 2模板语法

@Component({ 
    selector: 'app', 
    template: require('./app.component.html'), 
    styles: [require('./app.component.css')], 
    directives: [ ROUTER_DIRECTIVES ],   
}) 

以下两种说法有何不同?这里需求函数的作用是什么?

  • 模板:要求( './ app.component.html ')
  • 模板:' ./app.component.html'

在上述声明中的负载是否需要HTML模板异步?

回答

1

以下两种说法有何不同?

那么需要为CommonJS的一部分,的require('./app.component.html')的结果将是模板字符串, 但templateUrl场预计路径.html模板。

所以如果你打算使用require,你必须使用template而不是templateUrl

有由whihc您可以加载您的模板

  1. 使用要求你必须分配到模板像这样不同的方式:

    template: require('./app.component.html'), 
    
  2. 使用这样的简单路径: -

    templateUrl: 'app/app.component.html', 
    
  3. 通过设置module.id property in the @component注释,通过这样做angular将查看当前文件夹 中的模板insetad查看根目录。像这样:

    @Component({ 
        selector: 'my-app', 
        moduleId: module.id, 
        templateUrl: 'app.component.html', 
        styleUrls: ['app.component.css'] 
    }) 
    

看到这里获取更多信息http://schwarty.com/2015/12/22/angular2-relative-paths-for-templateurl-and-styleurls/

+1

这是否意味着模板:要求(” ./ app.component。html')语句将拉取模板文件;以字符串的形式读取其内容并在运行时将其分配给模板?还是在编译时本身发生? –

+0

我不知道运行时/ compileTime,但是这个语句将拉模板作为字符串,并显示为视图。 –

0

您现在可以同步或异步加载模块。同步方式是一个在CommonJS的定义非常简单 - 这是同步的方式,同步加载然而块脚本执行,直到模块加载

var mymod = require('myModule'); 
// Call the exported function "hello()" 
mymod.hello(); 

,所以它可能是更好的异步加载模块:

require('myModule', function(mymod) { 
    // Call the exported function hello 
    mymod.hello(); 
}); 

你可以做到这一点的方式 -

import {Component} from 'angular2/core'; 

@Component({ 
    selector: 'my-app', 
    moduleId: module.id, 
    templateUrl: 'app.component.html', 
    styleUrls: ['app.component.css'] 
}) 

设置的moduleId:module.id在@Component装饰是这里的关键。如果你没有,那么Angular 2会在根目录下查找你的文件。所以你不需要require()了。希望它会有所帮助:)