Angular2HelloWorld

Angular 2 Hello World

描述在上一章中,我们研究了如何为Angular 2设置开发环境。在本章中,我们创建一个示例来显示 Hello World 文本。 例子下面的例子描述了如何在Angular 2中显示一个简单的文本:<!DOCTYPE html>

<html>

<head>

<title>Hello World</title>

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/es6-shim.min.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system-polyfills.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2-polyfills.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/typescript.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/Rx.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2.dev.js"&gt;&lt;/script&gt;

<script>

System.config({

transpiler: 'typescript',

typescriptOptions: { emitDecoratorMetadata: true },

packages: {'app': {defaultExtension: 'ts'}}

});

System.import('/angular2/src/app/hello_world_main')

.then(null, console.error.bind(console));

</script>

</head>

<body>

<my-app>Loading...</my-app>

</body>

</html>

上述代码包括以下配置选项: 您可以使用 typescript 版本配置 index.html 文件。 在使用 transpiler 选项运行应用程序之前,SystemJS将TypeScript转换为JavaScript。 如果在运行应用程序之前没有翻译到JavaScript,您可能会看到浏览器中隐藏的编译器警告和错误。 当设置了 emitDecoratorMetadata 选项时,TypeScript会为代码的每个类生成元数据。 如果不指定此选项,将生成大量未使用的元数据,这会影响文件大小和对应用程序运行时的影响。 Angular 2包含来自 app 文件夹的包,其中文件将具有 .ts 扩展名。 接下来,它将从 app 文件夹加载主要组件文件。 如果没有找到主要组件文件,那么它将在控制台中显示错误。 当Angular调用main.ts中的引导函数时,它读取Component元数据,找到“app"选择器,定位一个名为app的元素标签,并在这些标签之间加载应用程序。 要运行代码,您需要在 app 文件夹下保存以下 TypeScript(.ts)文件。hello_world_main.tsimport {bootstrap} from "angular2/platform/browser"

import {MyHelloWorldClass} from "./hello_world_app.component"

bootstrap(MyHelloWorldClass);

现在我们将在TypeScript(.ts)文件中创建一个组件,如下所示:hello_world_app.component.tsimport {Component, View} from "angular2/core";

@Component({

selector: 'my-app'

})

@View({

template: '<h2>Hello World !!</h2>'

})

export class MyHelloWorldClass {

}

@Component 是一个装饰器,它使用配置对象来创建组件。 选择器创建组件的实例,找到< my-app> 父HTML中的标记。 @view 包含一个模板,用于告诉Angular如何渲染视图。 export 指定组件在文件外部可用。输出让我们执行以下步骤,看看上面的代码如何工作:将上面的HTML代码保存为index.html文件,如同我们在环境章节中创建的,并使用上面的包含.ts文件的应用程序文件夹。 打开终端窗口并输入以下命令: npm start 稍后,浏览器选项卡应打开并显示输出,如下所示。或者,您可以以其他方式运行此文件:将上面的HTML代码另存为您的服务器根文件夹中的 angular2_hello_world.html 文件。将此HTML文件打开为http://localhost/angular2_hello_world.html,并显示如下所示的输出。