angular - 如何禁用与 angular 中的 api 匹配的特定输入

我正在处理一个 Angular 项目,员工将登录,然后从 Angular date 选择器中选择一个月。 table 将弹出包含所选月份的日期,并在每一天下输入 1 或 0(如果他那天工作与否),

我的问题是:我不知道如何禁用周六和周日的输入+假期。

假期我可以通过使用法国政府的 Api(公共和免费)来获得主题,您会在下面找到一个注释,我在其中进一步解释了我的应用程序的功能。

我的 ts 文件:

import { DatePipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { ApiService } from './api.service';

import {
  MomentDateAdapter,
  MAT_MOMENT_DATE_ADAPTER_OPTIONS,
} from '@angular/material-moment-adapter';
import {
  DateAdapter,
  MAT_DATE_FORMATS,
  MAT_DATE_LOCALE,
} from '@angular/material/core';
import { MatDatepicker } from '@angular/material/datepicker';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';

import * as moment from 'moment';
import { Moment } from 'moment';

export const MY_FORMATS = {
  parse: {
    dateInput: 'MM/YYYY',
  },
  display: {
    dateInput: 'MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
    },

    { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
  ],
})
export class AppComponent {
  joursFeries: any;
  annee: number = 2022;

  totale: number = 0;
  form!: FormGroup;
  i!: number;
  monthDates: String[] = [];
  yearSelected!: number;
  monthSelected!: number;
  daysOfMonth!: number;
  daysArray!: FormGroup;

  constructor(
    public datePipe: DatePipe,
    private fb: FormBuilder,
    private api: ApiService
  ) {}

  ngOnInit(): void {
    let today = new Date();
    let todayMonth = today.getMonth() + 1;
    let todayYear = today.getFullYear();
    const month = Number(todayMonth);
    const year = Number(todayYear);
    this.monthDates = this.getDaysArray(year, month);
    this.daysOfMonth = this.monthDates.length;
    this.form = this.fb.group({
      year,
      month,
      days: this.fb.array([]),
    });

    for (this.i = 0; this.i < this.daysOfMonth; this.i++) {
      this.addDay();
    }

    this.api.getJoursFeries(year).subscribe(
      (data: JSON) => {
        this.joursFeries = data;
        console.log(this.joursFeries);
        // console.log(data);
      },
      (error: HttpErrorResponse) => {
        console.log(error);
      }
    );
  }

  getDaysArray = (year: number, month: number) => {
    const names = Object.freeze([
      'Sun',
      'Mon',
      'Tue',
      'Wed',
      'Thu',
      'Fri',
      'Sat',
    ]);
    const date = new Date(year, month - 1, 1);
    const result = [];
    while (date.getMonth() == month - 1) {
      result.push(`${date.getDate()}
      ${names[date.getDay()]}`);
      date.setDate(date.getDate() + 1);
    }
    return result;
  };

  date = new FormControl(moment());

  setMonthAndYear(
    normalizedMonthAndYear: Moment,
    datepicker: MatDatepicker<Moment>
  ) {
    const ctrlValue = this.date.value;
    ctrlValue.month(normalizedMonthAndYear.month());
    ctrlValue.year(normalizedMonthAndYear.year());
    this.date.setValue(ctrlValue);
    datepicker.close();
  }

  dateChanged($event: MatDatepickerInputEvent<Date>) {
    let monthChosen = moment($event.target.value).format('MM');
    let yearChosen = moment($event.target.value).format('yyyy');
    let month = Number(monthChosen);
    let year = Number(yearChosen);
    this.monthDates = this.getDaysArray(year, month);
    this.daysOfMonth = this.monthDates.length;
    const arr = <FormArray>this.form.controls['days'];
    arr.controls = [];
    this.form.controls['month'].setValue(month);
    this.form.controls['year'].setValue(year);
    for (this.i = 0; this.i < this.daysOfMonth; this.i++) {
      this.addDay();
    }
    this.api.getJoursFeries(year).subscribe(
      (data: JSON) => {
        this.joursFeries = data;
        console.log(this.joursFeries);
      },
      (error: HttpErrorResponse) => {
        console.log(error);
      }
    );
  }

  get days(): FormArray {
    return this.form.get('days') as FormArray;
  }

  addDay(): void {
    this.days.push(new FormControl('0'));
  }

  editDaysWorked() {
    console.log('Edit Days Worked');
    this.totaleDays();
  }

  totaleDays() {
    for (this.i = 0; this.i < this.form.value.length; this.i++) {
      this.totale = this.totale + this.form.value[this.i];
    }
  }
}

我的 CSS 文件:

.fixTop {
  margin-top: 100px;
  margin-bottom: 100px;
  margin-right: 100px;
  margin-left: 100px;
}
.form-control {
  /* padding: 30%; */
  padding-left: 10px;
  padding-right: 2px;
  size: 1;
}

.fixTable {
  margin-top: 50px;
  margin-right: 300px;
}
.top {
  margin-top: 100px;
}
.aaa{
  margin-inline: 15%;
}

.example-month-picker .mat-calendar-period-button {
  pointer-events: none;
}

.example-month-picker .mat-calendar-arrow {
  display: none;
}
.right {
  margin-left: 200px;
}

.c5 {
  background-color: blue;
}

我的 html 文件:

<div class="ms-5 mx-5 col-1">
  <mat-form-field appearance="outline">
    <mat-label>Month and Year</mat-label>
    <input
      matInput
      [matDatepicker]="dp"
      [formControl]="date"
      (dateChange)="dateChanged($event)"
    />
    <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
    <mat-datepicker #dp startView="year" panelClass="example-month-picker">
    </mat-datepicker>
  </mat-form-field>
</div>

<div>
  <form [formGroup]="form">
    <div class="mt-5" formArrayName="days">
      <div class="d-flex mx-5 me-5 mb-5">
        <table class="table">
          <thead>
            <tr>
              <th scope="col" *ngFor="let date of monthDates">{{ date }}</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td
                *ngFor="
                  let j of [].constructor(this.daysOfMonth);
                  let day;
                  of: days.controls;
                  let i = index
                "
              >
                <input
                  class="form-control"
                  [id]="i"
                  type="text"
                  formControlName="{{ i }}"
                  name="day"
                  [value]="form.value.days[i]"
                  size="1"
                  maxlength="1"
                />
              </td>
            </tr>
          </tbody>
        </table>
        <br />
      </div>
      <div [align]="'center'">
        <button mat-raised-button color="primary">save</button>
        <button
          class="ms-3"
          mat-raised-button
          (click)="editDaysWorked()"
          color="warn"
        >
          edit
        </button>
      </div>
    </div>
  </form>
</div>

{{ joursFeries | json }}

我的服务文件:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class ApiService {
  private apiBaseUrl = 'https://calendrier.api.gouv.fr/jours-feries/metropole';

  constructor(private http: HttpClient) {}

  getJoursFeries(annee: number): Observable<any> {
    return this.http.get<any>(`${this.apiBaseUrl}/${annee}.json`);
  }
}

https://stackblitz.com/edit/angular-ivy-efx4jq?file=src/app/api.service.ts

员工登录他的页面后,他会发现一个Angular datePicker和一个table,table包含他所在月份的天数,在每一天下都有一个输入,如果他可以输入1当天工作或 0 如果没有,默认 value 是 0 ,在他用正确的 values 填写 table 后,他可以点击保存,数据将存储在数据库中,如果他想更改月份他将单击 datpicker 并更改 dates

回答1

MatDatepicker API 提供过滤功能。您可以使用它来过滤周末和节假日。 https://material.angular.io/components/datepicker/overview#datepicker-filter

[matDatepickerFilter]="myFilterFunc" 属性添加到日期选择器的输入中,将允许您应用您选择的过滤器。在这种情况下,myFilterFunc 将是组件类中的一个函数,它接受 date 并返回 true 或 false。

例如:过滤周末

myFilterFunc = (d: Date | null): boolean => {
  const day = (d || new Date()).getDay();
  // Prevent Saturday and Sunday from being selected.
  return day !== 0 && day !== 6;
};

您可以使用您的服务逻辑提前提取假期,然后将其集成到这种过滤器功能中。

相似文章