Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style the nested firstElementChild in native Element Angular

I have this following Structure where the there are nested child components in Parent Component and i need to lay the focus on the Child component div programmatically.

I have reproduces this stackblitz for the above problem.

If you see the ts file, I have done the following

 ngAfterViewInit(){
  console.log(this.test);
  this.test.toArray()[1].nativeElement.focus();
  this.test.toArray()[1].nativeElement.firstElementChild.nativeElement.focus(); //this dosent work
 }

The console.log returns me a query list of divs (in my original case a list of components) and in that I have a firstElementChild a (component) whose firstChildElement is a div I need to style and add focus on. But I am unable to do so as if you check the stacktrace it returns Cannot read property 'focus' of undefined.

In simple works the Structure:

ParentComponent -> viewChild gets me Query List of Child -> the array element has components -> each component has a firstElementChild -> property that has a div that I need to put focus on

UPDATE

Thanks all for your feedback and help really appreciated but now the thing is It works but only if i give tab index for all the nested divs i was hoping that it trickles down the child the tab index. this is the problem. Any work around to this problem as this way i need to modify the template fro all my nested components in the broader sense

like image 706
INFOSYS Avatar asked Feb 05 '26 22:02

INFOSYS


1 Answers

Try to change

this.test.toArray()[1].nativeElement.firstElementChild.nativeElement.focus(); //this dosent work

to

this.test.toArray()[1].nativeElement.firstElementChild.focus(); //this should work :-)

nativeElement.firstElementChild is NOT an ElementRef but already an HTMLElement => it doesn't have a property nativeElement.

like image 143
Dieter Rehbein Avatar answered Feb 09 '26 07:02

Dieter Rehbein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!