简体   繁体   English

Angular 动态日期选择器和动态下拉验证和表单提交

[英]Angular dynamic Date-picker and dynamic dropdown validation and form submit

I am newbie in Angular and stuck at once place.我是 Angular 的新手,并且卡在了一个地方。 I want to get JSON on form submit.我想在提交表单时获得 JSON。 The form is custom combination of dynamic dropdown and dynamic mat datepicker .表单是动态下拉列表动态 mat datepicker的自定义组合。 I am not able to validate or get data on submit.我无法验证或获取提交数据。 Here is my code of component.ts and html files这是我的 component.ts 和 html 文件的代码

    import { Component, OnInit, Input } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

var R_DATA = {
  "grid": {
    "row": {
      "col": [
        {
          "size": 3,
          "label": "Branch",
          "type": "dropdown",
          "id": "branchCd",
          "default": "${userBranchCd}",
          "ddCd": "4"
        },
        {
          "size": 3,
          "label": "From Date",
          "id": "fromDt",
          "type": "date",
          "default": "${currentDate-7}"
        },
        {
          "size": 4,
          "label": "To Date",
          "id": "toDt",
          "type": "date",
          "default": "${currentDate}"
        }
      ]
    }
  }
}

@Component({
  selector: 'app-dynamic-report-viewer',
  templateUrl: './dynamic-report-viewer.component.html',
  styleUrls: ['./dynamic-report-viewer.component.scss']
})
export class DynamicReportViewerComponent implements OnInit {
  testData: string;
  reportData: any;
  showReport: boolean = false;
  @Input() reportForm: FormGroup;
  @Input() reportScreenTitle: string;
  captureParent: any;
  formCol: any;
  formName: string;
  formSubmitted: {};
  constructor() {
    // const currentDate = new Date().getDate;
    // this.minDate = new Date(currentDate - 7);
    // this.maxDate = new Date(currentDate + 1, 11, 31);
   }

  ngOnInit(): void {
    this.testData = '15';
    this.reportData = R_DATA.grid;
    // console.log(this.reportData);
    this.formCol = this.reportData.row.col
    
    
    if(this.reportData){
      this.formCol.forEach(element => {
          this.formName = element.id
      });
    }
    this.reportForm = new FormGroup({
      "this.formName" : new FormControl('', Validators.required)
    })

    
    // this.reportForm.controls['date'].hasError('matDatepickerMin')
    // this.reportForm.controls['date'].hasError('matDatepickerMax')
  }
  captureData(e: any) {
    this.captureParent = e.text
  }

  
  myFilter = (d: Date | null): boolean =>{
    const day = (d || new Date()).getDay();
    return day !== 0
  }

  loadReport() {
    this.formSubmitted = {
      'this.formName': this.captureParent
    }

    //let getReport = []
    alert(JSON.stringify(this.formSubmitted))
    // console.log(getReport);
    this.showReport = false;
  }

  onSubmit(){
    // alert(JSON.stringify(this.reportForm.value));
    alert('hi');
  }
}

and here is the respective html这是各自的 html

<h2>{{reportScreenTitle}}</h2>
<div class="card" [formGroup]="reportForm" (ngSubmit)="reportForm.valid && onSubmit()">
    <div class="card-header mt-2">
        <div class="grid" *ngIf="reportData">
            <div class="row" *ngIf="reportData.row">
                <div class="col col-{{list.size}}" *ngFor="let list of reportData.row.col">
                    <div [ngSwitch]="list.type">
                        <!-- <input *ngSwitchCase="'textbox'"  [formControlName]="list.id" [id]="list.id" [type]="list.type"> -->
                        <mat-form-field appearance="legacy" *ngSwitchCase="'date'">
                            <mat-label>{{list.label}}</mat-label>
                            <input matInput [matDatepicker]="picker" [id]="list.id" [formControlName]="list.id">
                            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                            <mat-datepicker #picker></mat-datepicker>
                        </mat-form-field>
                        <div *ngSwitchCase="'dropdown'">
                            <app-dynamic-dropdown (valueChange)="captureData($event)" id="{{list.id}}" name="{{list.id}}" ddCd="{{list.ddCd}}" displayLabel="{{list.label}}" isMandatory="true">
                            </app-dynamic-dropdown>
                        </div>

                    </div>
                </div>
                <div class="col">
                    <button class="btn btn-warning" (click)=loadReport()>Submit</button>
                </div>
            </div>
        </div>
    </div>
    <div class="card-body">
        <iframe id="dynamic_report_iframe" *ngIf="showReport" width="100%" height="500px" ></iframe>
    </div>
</div>

Any help or suggestion will be appreciated!任何帮助或建议将不胜感激!

I suggest you use angular FormBuilder to build out the form group of the reactive form.我建议你使用 angular FormBuilder来构建反应表单的表单组。 It helps arrange the format of the result of the submitted form value.它有助于安排提交表单值结果的格式。 FormBuilder arrangement also makes it easy for adding Validations to FormControls. FormBuilder 的安排也使得向 FormControls 添加验证变得容易。

https://angular.io/guide/reactive-forms#using-the-formbuilder-service-to-generate-controls https://angular.io/guide/reactive-forms#using-the-formbuilder-service-to-generate-controls

This is Angular official demo -> https://stackblitz.com/angular/oyyrkpkkjldn?file=src/app/profile-editor/profile-editor.component.ts这是 Angular 官方演示 -> https://stackblitz.com/angular/oyyrkpkkjldn?file=src/app/profile-editor/profile-editor.component.ts

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

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