Tester
Tester

Reputation: 449

How can I access DOM elements in angular

I am tetsing a template driven form in angular, just testing not validating it. I have read that it can be done using a viewChild property but it seems to not work for me.

I create a reference like this in my one of my forms label:

<label #ref  id=.. class=...>

And now in my component I do this:

@ViewChild('ref') ref:ElementRef;

So, I suppose I created a valiable of type ElementRef that is viewChild of my input. So now I can use ref in my tests.

Inside my tests I do this:

let ref: HTMLElement:

it(....=>
{
ref = fixture.debugElement.query(By.css('ref')).nativeElement;
fixture.detectChanges();
expect(ref.innerHTML)toContain('Name');// or whatever
}

)

Now consider that the test, html and component files are separated from one another.

I still get errors of nativeElemnt property cannot be read. eventhough I have imported ElemntRef.

Is this the right way to access the DOM elemnts?? Or this viewChild doesnt make a referece to my label??

And again can I use the ID to access the form elements? What I have read they use a reference with #.

Thanks!!

Upvotes: 6

Views: 25941

Answers (1)

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

For direct access to DOM in Angular you can make judicious use of ElementRef

However Direct access to DOM elements is not a good practice because it leaves you vulnerable to XSS attacks.


Your AppComponent

import {Component, ElementRef} from '@angular/core';

@Component({
    selector: 'my-app'
})
export class AppComponent implements ngOnInit {

constructor(private _elementRef : ElementRef) { }

ngOnInit(): void
{
  this.ModifyDOMElement();
}

 ModifyDOMElement() : void
 { 
   //Do whatever you wish with the DOM element.
   let domElement = this._elementRef.nativeElement.querySelector(`#someID`);
 } 
}

Your HTML

<p id="someID"></p>

Upvotes: 8

Related Questions