Angular2 How to get reference of HTML elements generated dynamically

前端 未结 4 1932
傲寒
傲寒 2020-12-30 20:33

I have this inputs generated dynamically:

  
相关标签:
4条回答
  • 2020-12-30 20:57

    There is a class called ElementRef class

    It gives your permit direct access to the current component or directive hosting DOM.

    You can use ElementRef.nativeElement to get a HTML element, then you can access to html element properties to make your modification by using jQuery or Renderer class provided by Angular 2.

    Example with ElementRef and Renderer:

    import { Directive, ElementRef, Input, Renderer } from '@angular/core';
    @Directive({ selector: '[myHighlight]' })
    export class HighlightDirective {
        constructor(el: ElementRef, renderer: Renderer) {
           renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
        }
    }
    
    0 讨论(0)
  • 2020-12-30 21:00

    The only response is

    let elem:Element = document.getElementById("myProgrammaticallyChosenIndex")

    No other angular weird ceremony needed

    Tested on angular 4+

    0 讨论(0)
  • 2020-12-30 21:17

    You can access the DOM by the elementRef.

    Inject it through your constructor by

    constructor(myElement: ElementRef) { ... }
    

    And access the DOM element by the nativeElement property

    myElement.nativeElement.select("#blabla")
    
    0 讨论(0)
  • 2020-12-30 21:20

    Use ElementRef class from @angular/core to get the parent element and then create an HTMLElement to get its dynamic elements by class name.

    Component:

    declare var $: any; //intentional use of jQuery-not recommended though
    
    @Component({
      selector: 'my-app',
      template: `
        <input type='button' (click)='addDiv()' value='Add New Div' />
    
        <input type='button' (click)='selectDiv()' value='Select' />
      `
    })
    export class App {
      constructor(private elRef: ElementRef) {
      }
    
      addDiv() {
        /*intentional use of jQuery for appending new div
         give a class to your dynamic elements*/
    
        $('my-app').append("<div class='foo'>Hello I'm Dynamic!</div>");
      }
    
      selectDiv() {
        //create a new HTMLElement from nativeElement
        var hElement: HTMLElement = this.elRef.nativeElement;
    
        //now you can simply get your elements with their class name
        var allDivs = hElement.getElementsByClassName('foo');
    
        //do something with selected elements
        console.log(allDivs);
      }
    }
    

    Working Plunker

    Edit: I used jQuery only for quick demo purpose here. Otherwise, you should not use jQuery with Angular.

    0 讨论(0)
提交回复
热议问题