elementRef.nativeElement.remove()对浏览器有任何负面影响吗?

Jon*_*002 5 dom angular

我正在设置超时以销毁Angular 2上可能在调用超时之前销毁的组件.超时以任一方式调用,它在组件的本机元素上执行.remove()(即使它不再在dom中).

如果元素被销毁并且超时执行以删除已经被破坏的组件,那么是否存在任何不可见的负面影响?

export class AnimationCloserComponent {
    public queryParams$;

    constructor(
        private router: Router,
        private elementRef:ElementRef,
        private activatedRoute:ActivatedRoute) {}    

    ngOnInit() {
        /* Will look for routing instructions with QueryParams to route and close this component. These instructions may sometimes not be available.. */
        this.queryParams$ = this.activatedRoute
            .queryParamMap 
            .map(params => {
                    let closeOutletName = params.get('closeOutlet') || null;
                    if (closeOutletName != null) {
                        this.router.navigate(['', { outlets: { [closeOutletName]: null }}]);
                    }
                    return params.get('closeOutlet') || null;
                }
            );

        /* This is meant to destroy the component if the router could not route away from it. */
        setTimeout(()=>{
            this.elementRef.nativeElement.remove();
        }, 1500);
    }    
}
Run Code Online (Sandbox Code Playgroud)

我真的想问一下,在我做这个练习之前,这样做是否合适.(已在下面澄清)

Max*_*kyi 4

在 Angular 不知情的情况下删除原生 DOM 元素几乎是不可能的。Angular 将所有与组件相关的节点(包括子组件)保留在名为View的抽象中。视图中的节点指向 DOM 元素。考虑以下设置:

ComponentA
   ComponentB
Run Code Online (Sandbox Code Playgroud)

视图层次结构将是这样的:

ComponentAView
    ElementNode('<b-comp>', document.createElement('<b-comp>'))
        ComponentBView
           ...
    ComponentClassNode(new ComponentB());
Run Code Online (Sandbox Code Playgroud)

如果你从 DOM 中删除第一个元素,<b-comp>Angular 对此一无所知。它将继续认为有可用的子组件。

这可能会导致意外的后果,例如当@ViewChildren您从 DOM 中删除子组件时,Angular 会报告该子组件。