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

Angular中mat-slide-toggle无法绑定[(ngModel)]的问题求助

Fixing "Can't bind to 'ngModel' since it isn't a known property of 'mat-slide-toggle'" in Angular 5

Hey there! Let's break down why you're hitting this error and how to fix it quickly.

The Root Cause

The [(ngModel)] directive isn't part of core Angular or Angular Material by default—it belongs to Angular's FormsModule. You need to explicitly import this module into your project to use two-way data binding with ngModel, even if you've already set up mat-slide-toggle.

Step-by-Step Fix

  1. Import FormsModule in your component's module
    Open the module file that declares your component (e.g., app.module.ts or a feature-specific module like settings.module.ts). Add the FormsModule import from @angular/forms, then include it in the imports array of your @NgModule:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms'; // 👈 Import this
    import { MatSlideToggleModule } from '@angular/material/slide-toggle'; // 👈 Ensure this is already imported
    
    import { YourComponent } from './your-component.component';
    
    @NgModule({
      imports: [
        BrowserModule,
        FormsModule, // 👈 Add to the imports array
        MatSlideToggleModule
      ],
      declarations: [YourComponent],
      // ... other module properties (like providers, bootstrap)
    })
    export class YourModule { }
    
  2. Verify your component and template setup
    Double-check that your component has the bound property defined, and your template syntax is correct:

    • Component code:
      import { Component } from '@angular/core';
      
      @Component({
        selector: 'app-your-component',
        templateUrl: './your-component.component.html'
      })
      export class YourComponent {
        isToggleOn = false; // 👈 Your bound property
      }
      
    • Template code:
      <mat-slide-toggle [(ngModel)]="isToggleOn">
        Toggle Status
      </mat-slide-toggle>
      

Why This Matters for Angular 5

In Angular 5, FormsModule isn't included automatically when creating a new project (unlike some later Angular versions). Since mat-slide-toggle only handles the UI rendering, Angular's form directives like ngModel require their own module to be available in your project.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:34:12