简体   繁体   中英

Angular 2 doesn't recognize DOM change

I using some angular 2 components in my project, and I need to change some of component's position. I use DOM to change the position first, like replaceChild or insertBefore, something like that. But I notice that angular 2 doesn't know the DOM change, seems like my DOM change is over the angular 2 life cycle. So, is there any way I can edit DOM in angular2 ? or some way I can change the order of components?

For you can understand what I'm doing, I'm building some components and I want to drag them and switch their position. I find a plug-in write in JQuery, you can find a gif on its GitHub site ( https://github.com/Barrior/DDSort/blob/master/img/ddsort.gif ). I want to implement something like that gif.

I find something maybe help on GitHub, but I don't know how to use it. https://github.com/angular/angular/blob/master/modules/angular2/src/core/linker/view_manager.ts

I realize this was asked a while ago, but for others that might be struggling with something like this... Angular uses zones which I believe monkey-patch asynchronous JavaScript operations.

To trigger DOM updates that might not otherwise be picked up by Angular, you can run your with zones...

import { NgZone } from '@angular/core';

@Injectable()
export class SomeService {

    constructor(private zone: NgZone) {}

    someFunction() {
        this.zone.run(() => {
            // Your code goes here!
        });
    }

}

Take a look at this blog on zones

To follow the best practice, developers should use ViewChild to modify/use DOM. Here is an example to show how to use ViewChild to get a DOM element. You can use a "#" to mark the element you want to use and get it on your component.

If you want to get a collection of child elements in a component you should use ViewChildren .

The question was asked when I started to Learn Angular, it's stupid question and I believe there are many beginners like manipulate DOM directly. Please update your DOM in "Angular Way".

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