Angular 5表单控件无值访问器错误求助:加name属性仍报错
Hey Krishna, let's work through these frustrating errors step by step. I'll break down why each one happens and how to fix them:
1. The <li> Tag with [(ngModel)] Issue
First up, your dropdown list item (<li>) isn't a standard Angular form control. Angular's [(ngModel)] directive only works with elements that implement the ControlValueAccessor interface—things like <input>, <select>, <textarea>, or custom form components you build yourself. A plain <li> doesn't have this built-in, so Angular has no idea how to handle the two-way binding.
Fix for the <li>:
Ditch the [(ngModel)] on the <li> entirely. Instead, track the selected state using a component property and update it in your click handler. Here's how to adjust your code:
First, add a property to your component class to track the selected gender:
selectedGender: string | undefined;
Then update your template (note I also fixed the inclues typo and extra comma in your click event):
<li class="dropdownfilter" *ngIf="this.arr.includes('Male')" (click)="getValueGender('Male', 1); selectedGender = 'Male'" [class.active]="selectedGender === 'Male'" > <a>Male</a> </li>
- Use
[class.active](or a custom class) to visually mark the selected item - Update
selectedGenderdirectly in the click event to track the user's choice - Remove the unused
[(ngModel)]="M"since we're handling selection manually
2. The <input> Tag Issue
For your phone number input, the same error usually pops up when you forget to import the FormsModule in your Angular module. [(ngModel)] is part of this module, so without it, Angular can't recognize form control bindings.
Fix for the <input>:
- Open your module file (e.g.,
AppModule.tsor the feature module where this component lives) - Import
FormsModulefrom@angular/formsand add it to theimportsarray:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // Add this line import { YourComponent } from './your-component.component'; @NgModule({ imports: [ BrowserModule, FormsModule // Add this to imports ], declarations: [YourComponent] }) export class YourModule { }
- Double-check that
contactNumberis declared in your component class (Angular will throw errors if the bound variable doesn't exist):
contactNumber: string = '';
Quick Recap of Common Causes for This Error
- Using
[(ngModel)]on non-form elements (like<li>,<div>) that don't implementControlValueAccessor - Forgetting to import
FormsModuleorReactiveFormsModulein your module - Typos in form control names or bound variable names (like your original
incluesinstead ofincludes)
内容的提问来源于stack exchange,提问作者Krishna

