I have a 10-input form. I added button cancel which is activating => confirmation modal which pop up when all input are filled. But I must do this is such way that modal will pop-up from 2 inputs are filled up ? Any suggestion? help articles? Angular
<app-task-form #form [draftInput]="data"></app-task-form>
<button mat-flat-button (click)="clickTwo(!form.valid)" i18n="@@CancelButton">
Cancel
</button>
clickTwo(result: boolean): void {
if (result == false) {
this.closeModal()
}
else {
this.dialogRef.close();
}
}
If user will input two fields and will press button modal shoud pop-up. If inputs are empty after pressing button form should close.
CodePudding user response:
Krzysztof. Perhaps your form has a FormGroup
interface, you can access to all controls of this form by calling method getRawValue()
or just get the value of property value
, like this.form.value
. In both cases you'll get object with interface
value/getRawValue: {
[key: string]: any;
}
Where key
is control name and any
value of that control. So, you can iterate through this object via Object.keys
or for in
loop, and check is in that object at least 2 "keys/controls" with some values. Hope it will help you. If your question is about something else, please clarify the question.
CodePudding user response:
<button mat-flat-button (click)="clickTwo(this.form.value)" i18n="@@CancelButton">
Cancel
</button>
clickTwo(form: Przetarg): void {
console.log(form)
for (let index = 0; index < Object.keys(form).length; index ) {
if (Object.keys(form).length > 4) {
console.log("Function : true")
// this.closeModal()
}
else {
console.log("Function : false")
}
}
}
This loop is not working for me :(
CodePudding user response:
Ok, @krzysztofbojarczuk. You made it in a wrong way. Let's fix it.
public clickTwo(form: Przetarg): void {
if (Object.keys(form).length > 4) {
// First of all, if you need to check form for amount of fields/controls, this condition should be here but not inside loop. So this "if" just checks if your form has more than 4 controls, but doesn't check is these controls are filled or not.
let counter = 0;
Object.keys(form).forEach((key: string) => {
// To iterate through the object keys we use 'Object.keys(): string[]' method that returns an array of 'keys: string', so we get names of object properties in the array, and we can iterate through the array with '.forEach()' method.
if (form[key]) {
// Here we are checking for value in object property. If value exist - not empty string, or undefined, or null, or false. Then we add 1 to a counter.
counter = counter 1;
}
});
if (counter >= 2) {
console.log(`Congrats! 2 or more fields filled in your form. We should show a confirmation modal!`);
// this.closeModal();
} else {
console.log(`User didn't fill at least 2 fields. We can remove this "else" statement if we don't need to do any actions in this case.`);
}
}
}
I hope it was helpful. If yes, please, vote for this answer