从Angular 1迁移至Angular 2:代码转换概念及示例解析
Let's break down how to convert your AngularJS triangle area calculator into Angular (v2+), step by step. I'll walk you through each part so you can clearly see how the old code maps to the new Angular structure.
First, let's recap what your original AngularJS code does:
It creates a simple app that calculates the area of a triangle (using
width * height / 2). It usesng-appto define the application boundary,ng-controllerto attach the business logic,ng-modelfor two-way data binding between the input fields and$scopevalues, and interpolation to display the real-time calculation result.
Step 1: Replace Controllers with Angular Components
Angular is built around components—self-contained units that hold both the template (HTML) and logic (TypeScript). This replaces the separate ng-controller and template setup from AngularJS.
Here's the component code (save this as triangle-calculator.component.ts):
import { Component } from '@angular/core'; @Component({ // This selector lets you use <app-triangle-calculator> in your root HTML selector: 'app-triangle-calculator', // The template replaces your original AngularJS HTML snippet template: ` <input type="text" [(ngModel)]="width" /><br /> <input type="text" [(ngModel)]="height" /><br /> <p>The result is: {{ calculateArea() }}</p> ` }) export class TriangleCalculatorComponent { // Initialize your values directly on the class (no more $scope!) width: number = 44; height: number = 22; // Optional (but cleaner): Move the calculation to a method calculateArea(): number { return this.width * this.height / 2; } }
Step 2: Configure the Angular Module
Angular requires a root module to bootstrap your app and manage dependencies. For two-way binding with [(ngModel)], you need to import FormsModule (this is a key difference from AngularJS, where ng-model worked out of the box).
Here's your root module code (app.module.ts):
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // Required for [(ngModel)] import { TriangleCalculatorComponent } from './triangle-calculator.component'; @NgModule({ // Declare your component so Angular recognizes it declarations: [TriangleCalculatorComponent], // Import required modules for browser support and two-way binding imports: [BrowserModule, FormsModule], providers: [], // Bootstrap your component to start the app (replaces ng-app) bootstrap: [TriangleCalculatorComponent] }) export class AppModule { }
Key Differences to Note
Let's directly map your AngularJS code to the new Angular implementation:
ng-app="myApp": Replaced by theAppModulebootstrapping yourTriangleCalculatorComponent—this is how Angular starts your application.ng-controller="myCtrl": Replaced by theTriangleCalculatorComponentclass. Instead of attaching properties to$scope, you define them directly on the component class, and Angular automatically makes them available to the template.ng-model: Becomes[(ngModel)](nicknamed "banana in a box" syntax) for two-way binding. Remember to importFormsModulein your module—this isn't optional!$scope.width/$scope.height: Replaced by class propertiesthis.widthandthis.height. The template accesses these directly without needing$scope.- Inline calculation (
{{width * height /2}}): This still works in Angular, but moving it to a method likecalculateArea()makes your template cleaner and the logic reusable (you could also use a getter property if you prefer).
How to Run the App
If you're starting from scratch, use the Angular CLI to create a new project (ng new triangle-app), replace the default component/module code with the snippets above, then run ng serve to launch the app in your browser. You'll see the same functionality as your original AngularJS code, but now on the modern Angular framework.
内容的提问来源于stack exchange,提问作者user1724708

