-1

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

Nomura Nori
  • 3,117
  • 6
  • 30
  • 66
  • I tried but got error, I edit my question. – Nomura Nori Sep 08 '17 at 19:59
  • Post a complete minimal example reproducing the problem. We can't explain why your code is incorrect without seeing your code. – JB Nizet Sep 08 '17 at 20:00
  • Would you please check code again? – Nomura Nori Sep 08 '17 at 20:19
  • 2
    You're mixing reactive forms, where the structure is created by your TS code (form groups and form controls), with template-driven forms, where the structure is created by the template (using ngModel). Don't. Pick one technique. – JB Nizet Sep 08 '17 at 20:24

1 Answers1

0

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();
}
Vinorth
  • 780
  • 7
  • 13