You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Angular 1迁移至Angular 2:代码转换概念及示例解析

Migrating from AngularJS to Angular: Your Triangle Area Calculator Example

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 uses ng-app to define the application boundary, ng-controller to attach the business logic, ng-model for two-way data binding between the input fields and $scope values, 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 the AppModule bootstrapping your TriangleCalculatorComponent—this is how Angular starts your application.
  • ng-controller="myCtrl": Replaced by the TriangleCalculatorComponent class. 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 import FormsModule in your module—this isn't optional!
  • $scope.width/$scope.height: Replaced by class properties this.width and this.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 like calculateArea() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:35:15