Angular7 Materials/CDK-拖放


Angular 7 CDK 添加的新拖放功能有助于从列表中拖放元素。我们将借助示例了解拖放模块的工作原理。该功能已添加到 cdk。我们需要先下载依赖,如下图:

npm install @angular/cdk --save
Drag and Drop Feature

完成上述步骤后。让我们在 app.module.ts 中导入拖放模块,如下图:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule , RoutingComponent} from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
import { MyserviceService } from './myservice.service';
import { HttpClientModule } from '@angular/common/http';
import { ScrollDispatchModule } from '@angular/cdk/scrolling';
import { DragDropModule } from '@angular/cdk/drag-drop';

@NgModule({
    declarations: [
        SqrtPipe,
        AppComponent,
        NewCmpComponent,
        ChangeTextDirective,
        RoutingComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        ScrollDispatchModule,
        DragDropModule
    ],
    providers: [MyserviceService],
    bootstrap: [AppComponent]
})
export class AppModule { }

DragDropModule 导入自 '@angular/cdk/拖放' 并将模块添加到导入数组,如上所示。

我们将使用来自 api 的详细信息, (http://jsonplaceholder.typicode.com/users) 要显示在屏幕上。我们有服务将从 api 获取数据,如下所示:

我的服务.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class MyserviceService {
    private finaldata = [];
    private apiurl = "http:// jsonplaceholder.typicode.com/users";
    constructor(private http: HttpClient) { }
    getData() {
        return this.http.get(this.apiurl);
    }
}

完成后调用 app.component.ts 里面的服务,如下图:

import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'Angular 7 Project!';
    public personaldetails = [];
    constructor(private myservice: MyserviceService) {}
    ngOnInit() {
        this.myservice.getData().subscribe((data) => {
            this.personaldetails = Array.from(Object.keys(data), k=>data[k]);
            console.log(this.personaldetails);
        });
    }
}

我们在个人详细信息变量中提供了所需的数据。现在让我们使用相同的方式显示给用户,如下所示:

<h3>Angular 7 - Drag and Drop Module</h3>
<div>
    <div *ngFor="let item of personaldetails; let i = index" class="divlayout”>
        {{item.name}}
    </div >
</div>

我们添加了 class = ”divlayout”,该类的详细信息在 app.component.css 中。

.divlayout{
    width: 40%;
    background-color: #ccc;
    margin-bottom: 5px;
    padding: 10px 10px;
    border: 3px solid #73AD21;
}

浏览器会显示如下画面:

Drag Drop

它不会拖放任何东西,我们需要在app.component.html中添加拖放cdk属性,如下图:

<h3>Angular 7 - Drag and Drop Module</h3>
<div cdkDropList
    #personList = "cdkDropList"
    [cdkDropListData] = "personaldetails"
    [cdkDropListConnectedTo] = "[userlist]"
    class = "example-list"
    (cdkDropListDropped) = "onDrop($event)" >
   
    <div *ngFor = "let item of personaldetails;
        let i = index" class = "divlayout" cdkDrag>
        {{item.name}}
    </div >
</div&t;

突出显示的是执行拖放所需的所有属性。当你在浏览器中签入时,它允许你拖动项目。它不会将其放入列表中,并且在你离开鼠标指针时将保持原样。

Drag Drop Module

在这里,它允许从列表中拖动项目,但是一旦你离开鼠标指针,它就会移动并固定在同一个地方。要添加drop功能,我们需要在app.component.ts中添加onDrop事件,如下图:

首先我们要导入dragdrap cdk模块,如下图:

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

app.component.ts 中的完整代码如下:

import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
import {CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'Angular 7 Project!';
    public personaldetails = [];
    constructor(private myservice: MyserviceService) {}
    ngOnInit() {
        this.myservice.getData().subscribe((data) => {
            this.personaldetails = Array.from(Object.keys(data),
            k=>data[k]);
            console.log(this.personaldetails);
        });
    }
    onDrop(event: CdkDragDrop<string[]>) {
        if (event.previousContainer === event.container) {
            moveItemInArray(event.container.data,
                event.previousIndex, event.currentIndex);
        } else {
            transferArrayItem(event.previousContainer.data,
            event.container.data,
            event.previousIndex,
            event.currentIndex);
        }
    }
}

onDrop 函数负责将拖动的项目放置在所需的位置。

它利用 moveItemInArray and transferArrayItem 我们已经从 cdk 拖放模块导入。

现在让我们在浏览器中再次查看演示:

Drag Drop Position

现在它允许你将项目拖放到所需的位置,如上所示。该功能运行非常流畅,没有任何闪烁问题,并且可以在需要时在你的应用程序中使用。