Angular 2.x selecting DOM element

后端 未结 5 864
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 01:06

I know it should be easy but angular 2.0 has no many examples yet..

In one of my components in some case I need to add class on my body tag. But my application is bo

相关标签:
5条回答
  • 2020-12-30 01:29

    DOM Manipulation in Angular 2 / 4 app

    To manipulate the DOM in Angular 2/4 apps, we need to implement the method ngAfterViewInit() of AfterViewInit. The method ngAfterViewInit() is called when the bindings of the children directives have been checked for the first time. In other words, when the view is initially rendered.

    The @ViewChild provides access to nativeElement. It is recommended to not access nativeElement inside the ngAfterViewInit() because it is not browser safe. Also, it's not supported by web workers. Web workers will never know when the DOM updates.

    The right way is to use renderer. The renderer needs to be injected to the component constructor. We need to provide an id reference to the HTML element on the view something like this:

    <p #p1></p>

    It shall be accessed by the corresponding coponent .ts file, something like this:

    
    export class SampleComponent implements AfterViewInit {
    
      @ViewChild("p1") p1;
    
      constructor(private renderer: Renderer2) //Renderer set to be depreciated soon
      { }
    
      ngAfterViewInit() {
    
        //recommended DOM manipulation approach
        this.renderer.setStyle(this.p1.nativeElement, //setElementStyle for soon to be depreciate Renderer
          'color',
          'red');
    
        //not recommended DOM manipulation approach
        //this.p1.nativeElement.style = "color:blue;";
      }
    
    }
    
    0 讨论(0)
  • 2020-12-30 01:36

    As of angular 2.4 you should inject the DOCUMENT and don't interact with any adapter:

    import { Component, Inject } from '@angular/core';
    import { DOCUMENT } from '@angular/platform-browser';
    
    @Component({})
    export class MyClass {
    
        constructor (@Inject(DOCUMENT) private document) { }
    
        doSomething() {
            this.document.someMethodOfDocument();
        }
    }
    

    Further reading: https://github.com/angular/angular/issues/8509

    0 讨论(0)
  • 2020-12-30 01:45

    I don't recommend direct DOM access from Angular, but you have a DOM hook via the ElementRef of your component. Once you have access to it you can use it directly or via jquery or any other DOM manipulation technique. I have included an example of how to use jquery to run general queries. If you are always going for the body tag you don't really need ElementRef, but it's useful for something that is relative to the root of the component.

    import {Component, ElementRef, OnInit} from '@angular/core';
    
    declare var jQuery:any;
    
    @Component({
        selector: 'jquery-integration',
        templateUrl: './components/jquery-integration/jquery-integration.html'
    })
    export class JqueryIntegration implements OnInit {
        elementRef: ElementRef;
    
        constructor(private elementRef: ElementRef) {
        }
    
        ngOnInit() {
            jQuery(this.elementRef.nativeElement).find('.moving-box').draggable({containment:'#draggable-parent'});
        }
    }
    

    More info here: http://www.syntaxsuccess.com/viewarticle/using-jquery-with-angular-2.0

    Demo: http://www.syntaxsuccess.com/angular-2-samples/#/demo/jquery

    0 讨论(0)
  • 2020-12-30 01:46

    As of Angular2 Version 2.0.0-beta.17.

    Attribute Directives in Angular2 will do this for you nicely.

    Please see this plunk written in TypeScript. This does what you want nicely.

    The directive file my-highlight.ts has the line:

    this.renderer.setElementClass(this.element, "red", true);
    

    This sets the CSS class on the element.

    While template.html has the actual element which is decorated with the directive [myHighlight]:

    <p [myHighlight]>Mouseover to highlight me!</p>
    

    This, to me, provides the least hack-ish answer to the question without any dependency on jqLite.

    0 讨论(0)
  • 2020-12-30 01:48

    Update

    I'm not sure if DOM is actually still supported in RC. The related statements aren't very clear. Something like

    DOM is only for internal use. Either access the DOM directly or use a custom renderer.

    I haven't see how a custom renderer might be implemented or how to provide an implementation depending on the current platform (webworker, server, DOM thread).

    Update This seems to be the Angular2 way

    import { DOM } from 'angular2/src/platform/dom/dom_adapter';
    
    DOM.addClass(DOM.query("body"), 'fixed');
    

    Import from .../src/... at your own risk. .../src/... is considered private implementation and you can't expect any guarantees that the API won't change without notice.

    I tried it in Dart and it works fine (not sure if the TS import above is correct though). In Dart DOM is exported by package:angular2/angular2.dart

    Original

    If you want to access a DOM element that's outside of your Angular application root, just use document.querySelector(), no need to involve Angular.

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