简体   繁体   中英

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

If you are using ngModel outside of the <form> you must specify [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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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