'Why do I have to put my code inside a setTimeout with zero milliseconds, to get it executed?
I'm using a custom third party library like bootstrap that has its own components. I can't apply CSS properties for inputs, for example, doing a validation to add an error or success border to the input, as the selector of the components of this library are not affected by CSS styles. This is an example:
<ds-input
(blur)="inactiveRut($event)"
class="w-full inputsThirdField inpMod"
id="rutInstitucion"
[helperMessage]="''"
[initialLabel]="'Rut institución/Prestador'"
size="s2"
labelOrientation="start"
>
</ds-input>
The blur method just try to add a class or another (depending on if the input is touched and empty or touched and filled, I cannot use either reactive forms as they don't recognize the formControlName attribute)
So, in an attempt to achieve it I tried to use old good document.getElementByClassName, because if I inspect the element, I can see it creates inside as children a lot of elements, like inputs, labels, and paragraphs, and I can see the classes they are given; please look at this screenshot:
Well, I tried to get them by the className on the ngAfterViewInit lifecycle hook and iterate them to add some kind of event listener to add or remove the "valid" ort "invalid" classes, like this:
let inputsDatosReembolso = document.getElementsByClassName('css-1f15fyx');
let inputsDatosReembolsoArray = Array.from(inputsDatosReembolso)
Array.from(inputsDatosReembolso).forEach((el) => {
let inputsInsideDs = Array.from(el.children)
console.log('inputsInsideDs', inputsInsideDs);
let input = inputsInsideDs[0]
console.log('input', input)
But to my surprise I didn't get anything printed on the console. So after hours I tried inserting the above code inside a setTimeOut method, with zero milliseconds, and to my surprise I got the elements logged on the console. Like this;
ngAfterViewInit() {
let inputsDatosReembolso = document.getElementsByClassName('css-1f15fyx');
setTimeout(() => {
Array.from(inputsDatosReembolso).forEach((el) => {
let inputsInsideDs = Array.from(el.children);
console.log('inputsInsideDs', inputsInsideDs);
let input = inputsInsideDs[0];
console.log('input', input);
}, 0);
});
}
and I got what I wanted; this:
Why does Angular not execute that code if it is not inside a setTimeOut? Is there a a more "Angular" elegant way to achieve the same result?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


