Angular中mat-slide-toggle无法绑定[(ngModel)]的问题求助
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
Import FormsModule in your component's module
Open the module file that declares your component (e.g.,app.module.tsor a feature-specific module likesettings.module.ts). Add theFormsModuleimport from@angular/forms, then include it in theimportsarray 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 { }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>
- Component code:
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

