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

AngularDart新手求助:如何让ngModel生效?模板编译器无法识别它

Fixing ngModel Recognition Issue in AngularDart

Hey there! I totally get how confusing this can be when you're just starting out with AngularDart. Let's break down what's going on and fix that ngModel problem step by step.

Why isn't ngModel being recognized?

The ngModel directive isn't included in the core angular package—it lives in the separate angular_forms package. That's why your template compiler doesn't know what it is until you add this dependency and set up the necessary imports/directives.

Understanding that pubspec.yaml diff snippet

That snippet you're seeing is a diff (a file change comparison) from the tutorial's project progression (from toh-0 to toh-1):

{toh-0 → toh-1}/pubspec.yaml @@ -8,2 +8,3 @@
8 8 dependencies:
9 9 angular: ^5.3.0
10 + angular_forms: ^2.1.2

Here's what each part means:

  • {toh-0 → toh-1}: This shows the change is from the "toh-0" version of the project to "toh-1"
  • @@ -8,2 +8,3 @@: This tells you the change affects lines 8-9 of the original file, and the updated file now has lines 8-10 (adding one new line)
  • The + sign next to line 10 means this is the new line you need to add to your own pubspec.yaml

Step-by-step fix

  1. Update your pubspec.yaml
    Open your project's pubspec.yaml file, find the dependencies section, and add the angular_forms line so it looks like this:

    dependencies:
      angular: ^5.3.0
      angular_forms: ^2.1.2
    
  2. Install the new dependency
    Run this command in your terminal to pull down the angular_forms package:

    pub get
    
  3. Import the forms package in your component
    In the Dart file where your component is defined (e.g., app_component.dart), add this import at the top:

    import 'package:angular_forms/angular_forms.dart';
    
  4. Add form directives to your component
    Update your @Component annotation to include formDirectives in the directives list—this lets AngularDart recognize ngModel in your template:

    @Component(
      selector: 'my-app',
      templateUrl: 'app_component.html',
      directives: [formDirectives], // Add this line
    )
    class AppComponent {
      // Your component logic here—make sure you have a variable bound to ngModel
      String username = '';
    }
    
  5. Test it in your template
    Now you can use ngModel in your template like this:

    <input type="text" [(ngModel)]="username" placeholder="Enter your name">
    <p>Hello, {{username}}!</p>
    

That should get ngModel working for you. If you run into any other snags, feel free to share more details!

内容的提问来源于stack exchange,提问作者bunthoeun khot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:52:32