简体   繁体   中英

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!!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM