【问题标题】:How to use ngModel with class data type in angular 2?如何在 Angular 2 中使用具有类数据类型的 ngModel?
【发布时间】:2017-09-08 19:55:23
【问题描述】:

我想在 Angular 2 项目中使用类实例进行双向数据绑定。可能吗? 为了便于理解,我缩短了代码

    ---- 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>

我试过了,但我得到了这个错误

ngModel 不能用于使用父 formGroup 指令注册表单控件。尝试使用 formGroup 的合作伙伴指令“formControlName”。示例:

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

    In your class:

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

或者,如果您想避免注册此表单控件,请在 ngModelOptions 中指明它是独立的:

  Example:


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

谢谢

【问题讨论】:

  • 我试过但出错了,我编辑我的问题。
  • 发布一个完整的最小示例来重现该问题。如果没有看到您的代码,我们无法解释为什么您的代码不正确。
  • 请您再检查一下代码好吗?
  • 您正在混合反应式表单,其中结构由您的 TS 代码(表单组和表单控件)创建,模板驱动表单,其中结构由模板创建(使用 ngModel) .不。选择一种技术。

标签: angular class angular-ngmodel two-way-binding


【解决方案1】:

这应该是可能的,但是,您必须使用组件装饰器在类的上下文中声明实例。例如

//import typescript person class

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-05
    • 2016-06-05
    • 2017-03-13
    • 2016-09-06
    • 2017-06-21
    • 2017-05-31
    • 2016-08-16
    • 1970-01-01
    相关资源
    最近更新 更多