Angular如何获取ngIf渲染的Dom元素 - 开发技术

  • 阿里云国际版折扣https://www.yundadi.com

  • 阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
    本篇文章和大家了解一下Angular如何获取ngIf渲染的Dom元素。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

    Angular获取普通Dom元素的方法

    通过模板变量名获取

    import { Component, ViewChild, AfterViewInit } from '@angular/core';
    @Component({
      selector: 'my-app',
      template: `
        <h2>Welcome to Angular World</h2>
        <p #greet>Hello {{ name }}</p>
      `,
    })
    export class AppComponent {
      name: string = 'Semlinker';
      @ViewChild('greet')
      greetDiv: ElementRef;
      ngAfterViewInit() {
        console.log(this.greetDiv.nativeElement);
      }
    }

    但我发现用这种方法获取ngIf渲染的元素时得到的是undefined

    <div *ngIf="isButtnGrop" (click)="dropBtnClick($event)">
      <div cdkDropList #dropList [cdkDropListConnectedTo]="_connectableDropLists" (cdkDropListDropped)="drop($event)">
        <div *ngFor="let item of itemDatas" (click)="onItemClick($event,item)" cdkDrag
          (cdkDragStarted)="startDragging($event)" [cdkDragData]="{ item }">
        </div>
      </div>
    </div>

    将static改成false 获取

    @ViewChild('dropList', { read: CdkDropList, static: false }) dropList: CdkDropList;
    ngAfterViewInit(): void {
        if (this.dropList) {
          console.log(this.dropList)
        }
      }

    通过这个也是实现了一个buttonGroup拖拽button到 列表的功能,列表的button也能拖拽到 buttonGroup
    用的也是Angular自带的 cdk/drag-drop

    import { CdkDragDrop, CdkDropList, moveItemInArray } from '@angular/cdk/drag-drop';

    自己实现的思路

    官网的文档和demo比较简单,没有讲到跨组件的实现,简单记录一下自己实现的思路。

    将需要拖拽的元素加入cdkDropList,并且在A组件和B组件都初始化的时候获取到需要拖拽的dom元素,将他们各自注册到store中,带上特殊的componentId。

    A、B组件加上cdkDropListConnectedTo 这决定着组件可以跨组件拖动到哪里,用_connectableDropLists变量。同样的,在页面初始化时,通过rxjs的流订阅特殊的componentId,去获取到当有拖拽list注册到store中时的变化,并且赋值给_connectableDropLists数组。

    const parentId = this.storeService.getProperty(this.pageId, this.componentId, 'parentId');
    this.dragDropService.getDragListsAsync(this.pageId, parentId.value)
          .pipe(takeUntil(this.destroy))
          .subscribe(dropLists => {
            this._connectableDropLists = dropLists || [];
          });
    this.storeService.getPropertyAsync(this.pageId, this.componentId, 'children')
          .pipe(takeUntil(this.destroy)).subscribe(result => {
            if (!result || result.length === 0) {
              this._children = [];
              this._dragData = [];
              this.changeRef.markForCheck();
            } else {
              const dropbuttonArray = result.filter((item) => {
                const itemType = this.storeService.getProperty(this.pageId, item, 'componentType');
                if (itemType === AdmComponentType.DropdownButton) return item;
              });
              if (dropbuttonArray.length > 0) {
                this._connectableDropLists = [];
                dropbuttonArray.forEach(comId => {
                  this.dragDropService.getDragListsAsync(this.pageId, comId)
                    .pipe(takeUntil(this.destroy))
                    .subscribe(dropLists => {
                      this._connectableDropLists.push(...dropLists);
                    });
                });
              }
            }
          });

    因为A组件是B组件的父级,所以需要通过当前组件id获取到父级id,再获取到拖拽元素

    通过cdkDragData 把拖拽的元素的value,id等值带上

    通过(cdkDropListDropped)="drop($event)",注册拖拽结束的回调事件

    drop回调事件处理拖拽结束后的数据处理,这里涉及到项目低代码的一些组件数据处理,大致是删除oldParent children, 然后新的parent节点加上,再更改当前组件的parent节点。同时这里涉及到buttongroup下面的button本身也可以互相拖拽的处理,所以也需要一层判断来特殊处理。

    drop(event: CdkDragDrop<any>) {
        if (event.previousContainer != event.container) {
          const { eventData } = event.item.data;
          const componentId = eventData[event.previousIndex];
          const oldParentId = this.storeService.getProperty(this.pageId, componentId, 'parentId', false)?.value;
          // delete oldParent children
          const oldParent = this.storeService.getProperties(this.pageId, oldParentId);
          const index = oldParent.children.indexOf(componentId);
          oldParent.children.splice(index, 1);
          // add newParent children
          const oldChildren = this.itemDatas.map(x => x.id.value);
          oldChildren.splice(event.currentIndex, 0, componentId);
          this.storeService.setProperty(this.pageId, componentId, 'parentId', { value: this.componentId }, [[this.pageId, componentId]]);
          this.storeService.setProperty(this.pageId, oldParentId, 'children', oldParent.children, [[this.pageId, oldParentId]]);
          this.storeService.setProperty(this.pageId, this.componentId, 'children', oldChildren);
          this.changeDetector.markForCheck();
          return;
        }
        moveItemInArray(this.itemDatas, event.previousIndex, event.currentIndex);
        const children = this.itemDatas.map(x => x.id.value);
        this.storeService.setProperty(this.pageId, this.componentId, 'children', children);
      }

    这样子组件和父组件的内部元素互相拖拽,也就能实现了

    以上就是Angular如何获取ngIf渲染的Dom元素的简略介绍,当然详细使用上面的不同还得要大家自己使用过才领会。如果想了解更多,欢迎关注片云行业资讯频道哦!

  • 阿里云国际版折扣https://www.yundadi.com

  • 阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

    “Angular如何获取ngIf渲染的Dom元素 - 开发技术” 的相关文章

    python爬虫的学习总结

    背景 基于django框架完成jira网页数据的爬取。由于对爬虫知识知道的太少,我开始了新的学习之旅。本文前半部分都是记录这一周主要的错误,如果想直接看最终成果,可以跳到本文“成功爬取”部分浏览。 学习爬虫知识 在知道了本项目可能需要爬虫后࿰...

    Android 12.0 根据包名授予WRITE

    1.概述 在12.0的系统产品开发中对于在项目中授予权限功能也是常见的功能在首次开机中默认授权运行时权限还有就是特殊权限比如悬浮窗权限WRITE_SETTINGS权限,安装第三方 app等等特殊权限的授予等等在最近的项目中就是需要根据包名默认授权WRITE_SETTINGS权限接下来就分析...

    Python二叉树怎么实现 - 开发技术

    本篇内容介绍了“Python二叉树怎么实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!Python实现二叉树Python实现二叉树可以使用面向对象编程的方式,通过定义...

    QtConcurrent

    当我们想在一个或多个辅助线程执行的同时做一些后台处理且无须使用QThread所提供的全部功能和灵活性时,就可以使用QRunnable和QtConcurrent::run()方法. QtConcurrent::run()函数的参数包含一个函数,一个或多个传递给...

    清除浮动之双伪元素

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,...

    在Windows和Linux系统中怎么安装PHP - 编程语言

    本篇内容主要讲解“在Windows和Linux系统中怎么安装PHP”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“在Windows和Linux系统中怎么安装PHP”吧! 一、 在Windows系统...