0

I am looking for how to access a DOM element in A4.

I am having a hard time trying to wrap my head around this... I've been reading about ElementRef, ViewChild, etc... but I still don't fully understand how to transverse the DOM elements in Angular 4. For example what would this jQuery statement be in A4?

$('events > ion-content > div.scroll-content > ion-grid:nth-child(1)').css({blah blah});

Like:

ElementRef.nativeElement - events > ion-content > div.scroll-content > ion-grid:nth-child(1)

How do I access that element in the fashion above - without adding any ids, classes, or #template tags? In certain situations I cannot access the html so I would like to know how to do this without the use of jQuery since it's frowned upon with Angular :[

RooksStrife
  • 1,647
  • 3
  • 22
  • 54
  • why do you need to do that? That's *probably* the question you want to ask. I admit that this is usually an annoying question to ask, but quite often when making the transition between jQuery and Angular-esque frameworks we don't explicitly need to do complex DOM element selection/manipulation. Don't be too descriptive, just say 'Im trying to do drag/drop etc' – nicholaswmin Nov 17 '17 at 00:32
  • @NicholasKyriakides Well in one case that I ran into this need was when I was trying to add a search bar into the ionic generated radio alert. I currently can use jQuery to append the search bar in, but as noted everywhere jQ is not A4 appropriate. Other times tracking elements height,scroll positions, etc. – RooksStrife Nov 17 '17 at 00:36
  • I am just looking for how to access the element - once there I can most likely figure out the rest. – RooksStrife Nov 17 '17 at 00:38

1 Answers1

0

How about this <ion-grid [class.add-this-class]="whenThisState === true"></ion-grid> ? or ngClass syntax if you fancy that.

Or do you want to get that element from a parent component or some other component ?

-EDIT-

If you cannot go to the angular template and do some binding there as I mentioned before, then basically you have 2 options Vanilla JS: private theElementYouAreLookingFor: HTMLElement

In ngAfterViewInit() lifecycle try to fetch it with JS and store it this.theElementYouAreLookingFor or

with by using the new Angular way @ViewChild('someVar') el:ElementRef; constructor(private renderer: Renderer2) {} and in ngAfterViewInit() this.el.nativeElement();

or by using Observables something like this: `const clickEl = document.querySelector('#my-button');

const click$ = Rx.Observable.fromEvent(clickEl, 'click');`

and then subscribe

click$.subscribe(...)

DrNio
  • 1,936
  • 1
  • 19
  • 25
  • Don't have access to the html element in this case. – RooksStrife Nov 17 '17 at 01:12
  • I will post another answer based on your feedback @RooksStrife, but can you please elaborate more how do you mean you don't have access to the angular template ? Is it inside an iframe ? – DrNio Nov 17 '17 at 06:42