0

I have used ngModel and formControlName together so I am getting warning in console. I want to remove that warning but I am not able to figure out if I am removing ngModel in it than with what should I replace it. I tried couple of code but it's not working.

This is my component.html file:

<mat-select
    formControlName="store"
    [(ngModel)]="this.form.value['store']"
    (selectionChange)="changestore()"
    multiple>
</mat-select>

This is my component.ts

changestore(){
 this.storeTechData.forEach((element:any)=> {
  if(this.form.value['store'].includes(element['store_id'])){
     element['active'] = true;
     }else{
      element['active'] = false;
     }
   });
 }

I tried reactive form and stuff but I am not getting required output. Someone please replace ngModel with reactive form or any thing else so that I will get the required output and also warning will not appear in the console

nate-kumar
  • 1,675
  • 2
  • 8
  • 15
Abhishek
  • 1
  • 1
  • you should remove `[(ngModel)]`. If you want to give an initial value give when create the formControl: `this.form=new FormGroup({store:new FormControl(2)})`or use setValue or pathValue – Eliseo Jan 03 '23 at 17:02

1 Answers1

0

With regards to forms in Angular:

You will want to stick to one paradigm when building forms in your app. In other words you will want to use either ngModel or formControlName but not both (which is why Angular warns you if both are included on a form element)

Reactive

component.html

<form [formGroup]="form">
  <mat-select
    formControlName="store"
    (selectionChange)="changestore()"
    multiple>
  </mat-select>
</form>

component.ts

form = new FormGroup({
  store: new FormControl('')
})

Template-driven component.html

<form>
  <mat-select
    [(ngModel)]="store"
    (selectionChange)="changestore()"
    multiple>
  </mat-select>
</form>

component.ts

store: string = ''

Generally speaking reactive forms are a more powerful paradigm to learn overall , so I would recommend becoming familiar with this approach (pros and cons of both). But for this simple use-case, either approach will work and is down to personal preference

Note: I have not attempted to address anything related to the changestore function as I'm not really sure what it is trying to achieve and there are some implementation details missing. But hopefully this is enough for you to work out what needs to be done for yourself

nate-kumar
  • 1,675
  • 2
  • 8
  • 15
  • Hi nate. I tried this but required output is not coming once i am removing ngModel and component.ts code was already there which you suggested – Abhishek Jan 04 '23 at 05:53
  • We have to change something in the function as well i guess – Abhishek Jan 04 '23 at 05:55
  • Could you expand your question to define what you mean by 'required output'? It would also be useful to provide some realistic data for `storeTechData` if this is relevant to your problem – nate-kumar Jan 04 '23 at 06:12