This doesn’t quite work.
I’m have an array of date pairs (start) and (end), and load three initially, and have two buttons, add and delete. The add button adds a new pair, but only if the last form group (which the pair of dates are in) is valid.
This works, but I want to be able to:
Make last element (the 3rd element) when the component is loaded, editable and to remove the validator.required condition from that control
Then when I add a 4th pair, I want to make the 3rd end date, non-editable, and add the validator.required condition, bu the 4th end date should be editable with the required condition.
Basically, the last end-date should always be optional (not required) and editable.
I’m struggling to get Angular to do this, for some reason, the last end date element is always required and never editable.
Sample code
protected addDatePair() {
const datesArray = this.datesInfo.get('datesArray') as FormArray;
if (datesArray.length > 0) {
const lastFormGroup = datesArray.at(datesArray.length - 1) as FormGroup;
if (lastFormGroup && lastFormGroup.valid) {
// add date to array in class
this.datesArray.push(9);
// create new end date control
const newEndDateControl = new FormControl(null, {
nonNullable: false,
validators: [],
});
newEndDateControl.reset();
const newFormGroup = this.datePairs();
// swap new control into new form group
newFormGroup.removeControl('endDate');
newFormGroup.addControl('startDate', newEndDateControl);
// add new form group to dates array
datesArray.push(newFormGroup);
// should probably only initialise new element, rather than all again
this.formGetters = this.initFormGetters(this.datesInfo);
// should probably initialise new error state matcher too
// need to add delay since,
// asynchronouse HTML may not have rendered the 4th element to DOM
// (a bit annoying!)
// I'd like to make the last End Date (i) modifiable and (ii) not required
setTimeout(() => {
const inputs = document.querySelectorAll(
'div[formArrayName="datesArray"] ' + 'input[id^="endDate"]'
);
const lastInput = inputs[inputs.length - 1] as HTMLInputElement;
if (lastInput) {
lastInput.removeAttribute('readonly');
lastInput.removeAttribute('required');
lastInput.removeAttribute('aria-required');
}
}, 1000);
} else {
console.log('last formGroup is not valid');
}
} else {
// TO IMPLEMENT
}
}
protected removeLastDatePair() {
// TO IMPLEMENT
}
Here is my stackblitz:
https://stackblitz.com/edit/stackblitz-starters-y2b7mc?file=src%2Fmain.ts
I want the delete button to do the same / similar thing.