How can I access a DOM element using a selector

In Angular2, is there a way to get an element through the NOT selector in the template, but inside the whole DOM?

+4
source share
3 answers

Of course, window.document.querySelectoror window.document.querySelectorAll.

+2
source

It is not recommended to access the DOM directly in angular2, as you bypass Angular2 renderer

To do this, you can use other functions of angular 2, for example: adding a link to this element.

Check this problem, it can help you: How to get dom element in angular 2

+7
source

, , IMHO . "".

Angularish-2 DOM; ElementRef ViewChild. , , .

ElementRef, , . , XSS. "" .

, -, , ViewChild.

:

<input #myinput type="text" />

, winky #myInput. , ol 'DOM id =' '. , , CSS .

In your code: Note. I use ES6 without annotations. but to get the same effect, you must use the @ViewChild annotation. It was good in TS (not in ES6 at all, it took me a while to get it together).

FYI I had to figure out how to do this because I wanted to implement an RxJS stream to do some debouncing and whatnot.

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

class HomeComponent {
    constructor( ) {}

    ngOnInit ( ) {
        // .nativeElement console.log out to what you'd expect.
        var inputBox = this.myInputRef.nativeElement;
        // left this in to demonstrate it works as plain ol' DOM elem,
        // if it didn't, this wouldn't work.
        var source = Rx.Observable.fromEvent(inputBox, 'click');
        ...
    }
}

HomeComponent.annotations = [
    new Component ( {
       templateUrl: './views/home/home.component.html',
       queries: { 'myInputRef': new ViewChild ( 'myinput' ) }
    } )
];
export { HomeComponent }

It works like a charm. About time, we had something like this in Angular. JQLite really never shortened it.

0
source

Source: https://habr.com/ru/post/1664926/


All Articles