📅  最后修改于: 2023-12-03 14:39:12.290000             🧑  作者: Mango
In this tutorial, we will learn how to create a basic "Hello World" application using Angular 2. Angular 2 is a powerful JavaScript framework developed by Google for building web applications. It allows you to build dynamic and interactive applications with ease.
Before we begin, make sure you have the following software installed on your machine:
Let's start by setting up our Angular 2 project. Follow the steps below:
Open your terminal/command prompt and navigate to the desired directory where you want to create the project.
Run the following command to create a new Angular project using the Angular CLI:
ng new angular2-hello-world
cd angular2-hello-world
ng serve
http://localhost:4200
. You should see the default Angular application running.To create the "Hello World" component, follow these steps:
src/app
directory:cd src/app
Create a new file called hello-world.component.ts
and open it in your favorite code editor.
In the hello-world.component.ts
file, add the following code:
import { Component } from '@angular/core';
@Component({
selector: 'app-hello-world',
template: `
<h1>Hello World</h1>
<p>Welcome to Angular 2!</p>
`
})
export class HelloWorldComponent {}
Now, let's update our main app component to use the newly created "Hello World" component:
Open the app.component.ts
file in the src/app
directory.
Update the code as follows:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>Welcome to Angular 2 - Hello World</h1>
<app-hello-world></app-hello-world>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {}
Open the app.module.ts
file in the src/app
directory.
Import the HelloWorldComponent
and add it to the declarations
array:
import { HelloWorldComponent } from './hello-world.component';
@NgModule({
declarations: [
AppComponent,
HelloWorldComponent
],
// ...
})
export class AppModule {}
Save the file.
Go back to your terminal/command prompt and make sure your Angular development server is still running. If not, start it again using ng serve
from the project directory.
Refresh your web browser, and you should now see the "Hello World" message displayed on the page.
Congratulations! You have successfully created a basic "Hello World" application using Angular 2.
Now you can explore Angular 2's features and start building more complex applications. Happy coding!
Note: This tutorial assumes you have a basic understanding of JavaScript and web development concepts. If not, it is recommended to learn those concepts before diving into Angular 2.