简体   繁体   English

如何使用angular2提交非形式元素

[英]how to submit a non-form element using angular2

      <tbody>
      <tr *ngFor="let gasType of staffConfig.gasTypes">
        <td class="col-md-3">
          <input class="gas-name form-control" type="text" [(ngModel)]="gasType.name" name="gasName"
                 [disabled]="!isStaffEnabled">
        </td>
      </tr>
      </tbody>
    </table>
  </div>

  <div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-heading">
      <h3 class="panel-title">
        <img src="/assets/brand-icon.png">
        <span>Brands</span>
      </h3>
    </div>

    <!-- Table -->
    <table class="table">
      <tbody>
      <tr *ngFor="let brand of staffConfig.brands;let i = index;">
        <td>
          <input class="form-control" type="text" [(ngModel)]="brand.name" name="brands"
                 [disabled]="!isStaffEnabled">
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</tab>

<button id="saveChangesBtn" type="button" class="btn btn-primary" disabled>Save Changes</button>

I want to bind the "save" button to a method in the component. 我想将“保存”按钮绑定到组件中的方法。 So I changed: 所以我改变了:

<button id="saveChangesBtn" type="button" (ngSubmit)="registerUser(registrationForm.value) class="btn btn-primary" disabled>Save Changes</button>

but then, if that's not a <form> how do I bind the fields to a model? 但是,如果那不是<form>如何将字段绑定到模型? In other words how can I send these fields to the server? 换句话说,如何将这些字段发送到服务器? I have to read them from the component and then assemble an object. 我必须从组件中读取它们,然后组装一个对象。 But how can I access the non-form model like registrationForm.value ? 但是,如何访问诸如registrationForm.value类的非表单模型?

If you are using ngModel outside of the <form> you must specify [ngModelOptions]={standalone:true} . 如果在<form>之外使用ngModel ,则必须指定[ngModelOptions]={standalone:true}

Template 模板

<div class="not-a-form">

    <input type="text" [(ngModel)]="model.foo" [ngModelOptions]="{standalone: true}" />

    <input type="text" [(ngModel)]="model.bar" [ngModelOptions]="{standalone: true}" />

    <button type="button" (click)="save(model)"> Send </button>

</div>

Component 零件

@Component({
selector: 'selector',
...
})

class SomeComponent {
 model: any = {};

  save(data) {
    console.log(data);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM