A191919
A191919

Reputation: 3442

Angular 8 post data from dynamic form

How to post data from all mat-select to controller?

<form class="example-form">
    <ng-container *ngFor="let drillBitProperties of DrillBitProperties$">
        <mat-form-field class="example-full-width" *ngIf="drillBitProperties.type=='dropdown'">
            <mat-label>{{drillBitProperties.label}}</mat-label>
            <mat-select>
                <mat-option *ngFor="let prop of drillBitProperties.options" [value]="prop">
                    {{prop}}
                </mat-option>
            </mat-select>
        </mat-form-field>
        <mat-form-field class="example-full-width" *ngIf="drillBitProperties.type=='int'">
            <input matInput placeholder="{{drillBitProperties.label}}" type="number">
        </mat-form-field>
    </ng-container>
    <button mat-button (click)="cancelDialog()">Cancel</button>
    <button mat-button (click)="sendData()">Post</button>
</form>

.ts

@Component({
  selector: 'app-add-product-dialog',
  templateUrl: './add-product-dialog.component.html',
  styleUrls: ['./add-product-dialog.component.css']
})
export class AddProductDialogComponent implements OnInit {

  DrillBitProperties$: any[]
  private headers = new HttpHeaders();

  constructor(
    public dialogRef: MatDialogRef<AddProductDialogComponent>,
    private http: HttpClient) {
    this.headers = this.headers.set('Content-Type', 'application/json; charset=utf-8');
  }

  ngOnInit() {
    this.DrillBitProperties$ = [
      { label: "Weight", name: "weight", type: "int" },
      { label: "Drill Bit Type", name: "drillBitType", type: "dropdown", options: ["Masonry", "SDS", "Universal"] },
      { label: "Drill Bit SharpAngel", name: "drillBitSharpAngel", type: "dropdown", options: ["118", "120", "135"] },
    ]
  }

  sendData() {
   //How to post here, selected data from dynamically generated `mat-select`? this.http.post...?
  }
}

Upvotes: 0

Views: 280

Answers (2)

ShivShankar Namdev
ShivShankar Namdev

Reputation: 298

you can try like this also

     <select (change)="onCountrySelectionChange($event.target.value)" formControlName="Country_ID">
              <option value="0">--Select--</option>
              <option *ngFor="let country of allCountry" value={{country.id}}>{{country.name}}</option>
            </select>

onCountrySelectionChange(countryId: string) {
this.FillStates(countryId);
this.selectedCountryID = countryId;}

private FillStates(countryId: string) {
this.commonDropdown.getStates(countryId).subscribe((data: {}) => {
  this.allState = data;
  this.allCity = null;
});

}

Upvotes: 0

D Pro
D Pro

Reputation: 1776

in your template:

<mat-select #select>

in the controller (I do not know the api of the MatSelect, you have to check it yourself):

@ViewChild("select", {static: false}) select: MatSelect;

sendData() {
   const data = this.select.getOption()
}

Upvotes: 1

Related Questions