Angular 2 Component - Access DOM (or create Component without template, purely from JS)

后端 未结 5 1288
滥情空心
滥情空心 2021-02-05 06:41

Trying to play with Angular 2 here... understood that it\'s still in alpha.

How do I access DOM elements from Component? Specifically, I would like to use other librarie

5条回答
  •  渐次进展
    2021-02-05 06:46

    Use ElementRef

    ElementRef will inject the current DOM node into your component. The ElementRef service will always be local to your current DOM node.

    Having injected it, you can get hold of the actual DOM node using nativeElement:

    var el = elementRef.nativeElement
    

    Once you have this, you can manipulate it it in any way you like, either using DOM scripting, or using a DOM wrapper like jQuery:

    $(el)
      .append('

    Some interesting Stuff') .addClass('my_class');

    But don't do this if you can help it

    Be aware that, as with Angular 1, the use of direct DOM manipulation is discouraged. You can get pretty much all of your work done using templates, and you should favour this way of working most of the time.

    Direct DOM manipulation leads to convoluted, hard to understand, hard to test code.

    There are times though, when it can seem like the best solution. For example, if you have to integrate with a third party, high-complexity framework like a graphing library.

    Here's a worked example (in ES6)

    var AppComponent = ng.core
      .Component({
        selector: "app",
        template:
        `
          
    Captured element
    ` }) .Class({ constructor: [ng.core.ElementRef, function(elementRef) { var el = elementRef.nativeElement el; }] })

提交回复
热议问题