Reputation: 1651
I have the following code:
required = computed(() => this.computeRequired(this.fields()));
private computeRequired(fields: FormField[]) {
console.log('Check fields:', fields);
// const req = signal<boolean>(false);
let req = false;
fields.forEach((field) => {
if (field.monkeyComp.state?.required) {
// req.set(true);
console.log(`TRUE`);
return true;
req = true;
}
});
// return req;
console.log(`req = ${req}`);
return req;
}
With this in the template:
@if (required()) {
<span class="form-required-note"> * Required </span>
}
This does some pretty weird stuff... As you can see, I've fiddled with a few small changes to see if helped.
The fields object is a signal input, and when this function runs, it's fully defined, and logs correctly. However, I get the cryptic log sequence:
TRUE
req = false
And the conditional element is in fact never shown in the DOM. There is some weirdness going on here that I don't understand!
Upvotes: 0
Views: 47
Reputation: 3203
As mentioned in the comment, forEach
loop does not exit when you return from it. If you are looking for the first occurence of the required field, use some
function.
private computeRequired(fields: FormField[]) {
// Looks for the first element which meets the condition and stops
let req = fields.some((field) => field.monkeyComp.state?.required});
console.log(`req = ${req}`);
return req;
}
Upvotes: 0