How to use ngModel with class data type in angular 2?

1.9k views Asked by At

I would like to use class instance for two way data binding in angular 2 project. is it possible? I shorten code for easy understanding

    ---- typescript ----

export class PackageOption {
    name: string;
    description: string;
...
}
import  { PackageOption }  from "./packageoption";
class PackageComponent extends Component implements OnInit {
    ...
    packageOptCurrent: PackageOption;
    ngOnInit() {
        this.packageOptCurrent = new PackageOption();
    }
...
}
    ---- templete ----
       <form [formGroup]="packageOptAddForm" #f="ngForm">
                <input type="text" formControlName="name" name="name" [(ngModel)] = "packageOptCurrent.name">
       </form>

I tried but I got this error

ngModel cannot be used to register form controls with a parent formGroup directive. Try using formGroup's partner directive "formControlName" instead. Example:

    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

this.myGroup = new FormGroup({
   firstName: new FormControl()
});

Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:

  Example:


<div [formGroup]="myGroup">
   <input formControlName="firstName">
   <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
</div>

Thanks

1

There are 1 answers

0
Vinorth On

This should be possible but, you have to declare the instance within the context of the class with component decorator. eg

//import typescript person class

@component({
    //some configuration
})
export class SomeClassComponent {
   mPerson = new Person();
}