1
votes

I am working on some simple form converting it from bootstrap to Material.

Altough I am working with Angular 6, the form is posted old-style on submit (no use of angular forms)

<form method="post" action="http://api.example.com/submit" id="user_form">

   <mat-form-field>
      <input matInput placeholder="name" name="username">
   </mat-form-field>


   <mat-form-field>
      <mat-select placeholder="user-type" name="usertype">
         <mat-option value="type1">type1</mat-option>
         <mat-option value="type2">type2</mat-option>
      </mat-select>
   </mat-form-field>

   <button type="submit">submit</button>

</form>

For simplicity, I'd would like to keep it this way, and don't use any javascript on submiting this form (no template-driven form OR reactive form).

the input is working great with adding name attribute to the imput and when I POST the form (click on the submit button) it sent to server as expected.

as for the mat-select, this data isn't sent to server in the post data. I guess that the former is native input where mat-select is a component.

Is there is a way to make this work? (again, without handling the form POST on the TS side)

4

4 Answers

2
votes

Found the answer.

Just use the native select like this:

<select matNativeControl placeholder="user-type" name="usertype" required>
  <option value="" disabled selected></option>
  <option value="type1">type1</option>
  <option value="type2">type2</option>
</select>
1
votes

No, you can't achieve that.

Unlike input field, mat-select is an angular component composed of div and span.

enter image description here

you can only send the its binded value.

1
votes

There's a way to set name attribute to the mat-select element directly.

In order to achieve it you need to use a [attr.name] construction. In the end the code would look like this.

   <mat-form-field>
      <mat-select placeholder="user-type" [attr.name]="'usertype'">
         <mat-option value="type1">type1</mat-option>
         <mat-option value="type2">type2</mat-option>
      </mat-select>
   </mat-form-field>

Demo: stackblitz.com

0
votes

I've been searching the same and solved this by binding a hidden input field. No need to write code-behind.

<mat-form-field>
  <mat-select #matSelect placeholder="user-type">
     <mat-option value="type1">type1</mat-option>
     <mat-option value="type2">type2</mat-option>
  </mat-select>
</mat-form-field>
<input type="hidden" name="usertype" [value]="matSelect.value" />