How to pass object as a param on ngModelChange angular 2

Issue

Notice: Im just starting with angular..
Ok, this is what I have:

<select class="form-control custom-select"
      [(ngModel)]=package
      (ngModelChange)="bindPackageCount(package)"
      formControlName="packagingProfile">
       <option *ngFor="let package of createdPackageData"
               [value]="package.count">
               {{package.package.name}} - {{package.type.name}}
       </option>
 </select>

By providing package.count as [value] of a select tag I can bind to it and pass it as param to bindPackageCount. What Im trying to do is to pass complete package (object) as a param not just the package.count (number). However, when I do that

bindPackageCount(package) {
    // package resolves to [Object object]
}

Per questions from others.. Yes, this is a reactive form, here is its creation:

createPackagingForm() {
    this.packagingForm = this._fb.group({
        packagingProfile: ['', Validators.required]
    });
}

any ideas? thx

Solution

Since you are using a reactive form, there is no need to use ngModel or ngModelChange. The changes will be caught with the formControlName. From what I understand, you want to bind the whole package object to your form, that can be achieved by using [ngValue], which in contrary to [value] binds the whole object. So your select would look like this:

<select formControlName="packagingProfile">
   <option *ngFor="let package of createdPackageData" [ngValue]="package">
           {{package.name}} - {{package.type}}
   </option>
</select>   

With that, you have the whole object stored in your formcontrol packagingProfile

DEMO

NB, Broken link

Answered By – AT82

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.