#angular #typescript
#angular #typescript
Вопрос:
У меня есть два входа / выхода из динамического поля ввода, которые зависят от выбранного значения. Я хочу сохранить данные из опции выбора и динамического поля ввода. мое динамическое поле ввода основано на том, сколько выбрано параметров выбора. Например, выбранные понедельник и вторник будут отображать как два поля ввода времени регистрации, так и время проверки.
Как создать динамическую ng-модель для хранения формата данных, подобного этому:
Вот мой HTML-код
<form role="form">
<div class="form-group">
<label>Profile Name</label>
<input type="text" class="form-control" placeholder=""
name="Table No"
[(ngModel)]="attendanceProfile.name" required>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label>Active Days</label>
<ng-select [items]="days" name="days"
bindLabel="id"
autofocus
loadingText="Loading ..."
[multiple]=true
bindValue="id"
placeholder="Select Active Days"
[(ngModel)]="attendanceProfile.days">
</ng-select>
</div>
</div>
{{attendanceProfile.days?.length}}
</div>
<div *ngFor="let dayys of attendanceProfile.days; let i =index ">
<div class="row" *ngIf ="attendanceProfile.days?.length > 0">
<div class="col-md-4">
<div class="form-group">
<label>Day</label>
<!-- {{attendanceProfile.days[i]}} -->
<input autocomplete="off" atp-time-picker type="text"
class="form-control" name="days"
id="days" value='{{attendanceProfile.days[i]}}'
placeholder="days" [(ngModel)]="multidaytime"
disabled/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Check In Time</label>
<input autocomplete="off" atp-time-picker type="text" class="form-control" name="checkInTime"
id="checkInTime" [(ngModel)]="[multidaytime].checkin"
placeholder="Select CheckIn Time"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Check Out Time</label>
<input autocomplete="off" atp-time-picker type="text" class="form-control" name="checkOutTime"
id="checkOutTime" [(ngModel)]="[multidaytime].checkout"
placeholder="Select CheckOut Time"/>
</div>
</div>
</div>
</div>
</form>
Ответ №1:
Я бы выполнил следующие шаги для достижения этой цели
// Create type for day
type IDay = "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday | "Sunday";
// Create Type for Multi Day Time
type IMultiDayTime = { [key in IDay]?: { checkin: string; checkout: string } };
export class AppComponent {
// Define the days
days: IDay[] = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
// Define a property to hold the active days selected
activeDays: IDay[] = [];
attendanceProfile: { name: string; days: IMultiDayTime } = {
name: "",
days: {}
};
// Create a multidaytime by reducing days to { Monday: {checkout: '', checkin: ''}, ...}
multidaytime: IMultiDayTime = this.days.reduce((prev, next) => {
return { ...prev, [next]: { checkin: "", checkout: "" } };
}, {});
// Create a function to handle change of the model values
changeModelValue = (value: IDay[]) => {
this.attendanceProfile.days = {};
this.days.forEach(day => {
if (!value.includes(day)) {
this.multidaytime[day] = { checkin: "", checkout: "" };
} else {
this.attendanceProfile.days[day] = this.multidaytime[day];
}
});
};
}
и в вашем html
<form role="form">
<div class="form-group">
<label>Profile Name</label>
<input
type="text"
class="form-control"
placeholder=""
name="Table No"
[(ngModel)]="attendanceProfile.name"
required
/>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label>Active Days</label>
autofocus
<ng-select [items]="days" name="days" loadingText="Loading ..." [multiple]="true"
[(ngModel)]='activeDays' (ngModelChange)='changeModelValue($event)'
placeholder="Select Active Days">
</ng-select>
</div>
</div>
</div>
<div *ngFor="let day of activeDays; let i =index ">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Day {{ day }}</label>
<input
autocomplete="off"
atp-time-picker
type="text"
class="form-control"
name="days"
id="days"
[value]="day"
placeholder="days"
disabled
/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Check In Time</label>
<input
autocomplete="off"
atp-time-picker
type="text"
class="form-control"
name="checkInTime"
id="checkInTime"
[(ngModel)]='multidaytime[day].checkin'
placeholder="Select CheckIn Time"
/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Check Out Time</label>
<input
autocomplete="off"
atp-time-picker
type="text"
class="form-control"
name="checkOutTime"
id="checkOutTime"
[(ngModel)]='multidaytime[day].checkout'
placeholder="Select CheckOut Time"
/>
</div>
</div>
</div>
</div>
</form>
<pre>{{ attendanceProfile | json }}</pre>