Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error 'No value accessor for form control with name' with ionic 5 and Angular 9 using reactive form

I'm working with ionic 5 and Angular 9. I'm trying to create a reactive form but I got the error 'No value accessor for form control with name: 'lastname''.

Here is my code :

export class ModalComponent implements OnInit {

  public form: FormGroup;

  constructor(private modalController: ModalController,
              private formBuilder: FormBuilder) { }

  ngOnInit(): void {
    this.initForm();
  }

  public close(): void {
    // using the injected ModalController this page
    // can "dismiss" itself and optionally pass back data
    this.modalController.dismiss({
      'dismissed': true
    });
  }

  public initForm(): void {
    this.form = this.formBuilder.group({
      firstname: ['', Validators.required],
      lastname: ['', Validators.required]
    });
  }

  logForm(){
    console.log(this.form.value)
  }
}
<form [formGroup]="form" (ngSubmit)="logForm()" novalidate>
    <ion-item>
      <ion-label>Last name</ion-label>
      <ion-input type="text" formControlName="lastname"></ion-input>
    </ion-item>
</form>

Edit : I just found the problem. I was missing the import IonicModule in my module.

like image 772
Alyaura Avatar asked Jan 26 '23 05:01

Alyaura


1 Answers

If your component (ModalComponent) is initialized from your own shared module (MyModule), you have to import IonicModule so it knows how to render with the value="" attribute.

my.module.ts:

...
import { IonicModule } from '@ionic/angular';

@NgModule({
  declarations: [ModalComponent],
  imports: [CommonModule],
  exports: [ModalComponent, FormsModule, ReactiveFormsModule, IonicModule],
})
export class MyModule {}

I was just dealing with this, and it took me a while to figure out the ReactiveForms code was trying to access the <input value=""> attribute which didn't exist because it was still an untransformed <ion-input> element.

like image 169
Raul Nohea Goodness Avatar answered Jan 27 '23 18:01

Raul Nohea Goodness