I am facing an issue related DOM Manipulation in angular. I have defined one array named colors in my component and then I am calling the service method and getting the colors data from the server and then assigning them into the colors array inside subscribe method. In HTML template using *ngFor loop, I am displaying that colors array data. Now I want to add some dynamic class or style to the HTML elements and for that, I am using ElementRef to access this element but I am not able to access it because the colors array is undefined initially. Now let me attach the code...
@Component({
selector: 'app',
template: "<div><li class="color" *ngFor="let color of colors">{{color}}</li></div>",
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
colors:any;
constructor(private elementRef:ElementRef, private renderer:Renderer2) {}
ngOnInit():void {
setTimeout(() => {
this.colors = ['red', 'yellow', 'green'];
}, 1000);
}
ngAfterViewInit():void {
const color = this.elementRef.nativeElement.querySelectorAll('.color');
console.log(color);
}
}
Here I am using the setTimeout function in this code which is behaving like a service because the service takes some time in getting the data from the server but in my code, I am using service.
Now If I am opening console in Developer Tools then I am getting NodeList [] this means I am not able to access DOM Element. I know the issue I am not able to access DOM element because my code for accessing DOM Element is running before the data assigning to the colors array and by default or initially colors array is undefined or empty. That's why I am getting NodeList [] in the console. But I am not able to understand how to solve this problem?.
Thanks in Advance.