Home > Back-end >  FormControlName Ionic 5.9.1 and Angular 12
FormControlName Ionic 5.9.1 and Angular 12

Time:11-24

I am trying to use the Reactive Forms on my app. I am using Angular 12 and Ionic 5.9.1. I checked the newest documents for in the ionic website and it seems there is no formControlName property. Using the formControlName property of the is the usual implementation that I see online. I just recently started exploring Ionic.

I am using the tabs template for Ionic. I have tabs1 and created a modal inside it with the form. The code for the form is as follows:

<ion-content>
  <ion-list lines="full" >
    <ion-list-header lines="full">
      <ion-label>
        Money Out Information
      </ion-label>
    </ion-list-header>
    
    <form [formGroup]="formGroup">
      <ion-item>
        <ion-label position="fixed">Amount</ion-label>
        <ion-input formControlName="amount" name="amount"></ion-input>
      </ion-item>
      <ion-button expand="block" fill="outline" (click)="submitForm()">Add Money Out</ion-button>
    </form>
  </ion-list>
</ion-content>

And my TS file is as follows

formGroup: FormGroup;

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

ngOnInit() {
  this.formGroup = this.formBuilder.group({
    amount: ['', Validators.required]
  });
}

submitForm() {
  console.log(this.formGroup.value);

  this.modalController.dismiss({
    'dismissed': true
  });
}

When I log the formGroup.value, amount still is blank. Thus, I am concluding that the binding has not happened. Is there a way to bind the FormControl to the ion-input? Did Ionic change the way to bind data to the forms? Is there a way to bind a FormControl directly to the ion-input instead of using the FormGroup?

CodePudding user response:

I was able to make it work by adding the new modal component to the declarations of the app.module.ts files. I use the ionic-cli to generate the component but I am not sure why it didn't add the component to the needed files.

CodePudding user response:

Make these changes on your TS file

export class Tab4Page implements OnInit, OnDestroy {
formGroup!: FormGroup;
...

constructor(
    private builder:FormBuilder,
  ) { }

ngOnInit() {
  this.formGroup = this.formBuilder.group({
    amount: ['', Validators.required]
  });
}
  • Related