Angular 8 post data from dynamic form

问题描述 投票:0回答:2

如何将数据从所有mat-select发布到控制器?

<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...?
  }
}
typescript angular8
2个回答
0
投票
在您的模板中:

<mat-select #select>

在控制器中(我不知道MatSelect的api,您必须自己检查):

@ViewChild("select", {static: false}) select: MatSelect; sendData() { const data = this.select.getOption() }


0
投票
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; });
}
© www.soinside.com 2019 - 2024. All rights reserved.