Angular 18 drag drop part of the data

Discussão em 'Angular' iniciado por TheWizardOfTN, Setembro 23, 2024.

  1. In this component.html:

    <div cdkDropListGroup>
    <div cdkDropList [cdkDropListData]="meals" class="makeMeal" (cdkDropListDropped)="drop($event)">
    <div *ngFor="let meal of meals" class="meal-drop">
    <img src="page_delete.png" (click)="deleteFood()" title="delete" />
    <h4>{{meal.name}}</h4>
    <label id="lblID" class="hidden">{{meal.id}}</label>
    </div>
    Add a meal:
    <input id="mealName" type="text" [(ngModel)]="mealName" name="mealName" required style="margin-left:10px;" />
    <img src="page_white_add.png" (click)="addMeal()" />
    </div>


    <p>My foods:</p>
    <div cdkDropList [cdkDropListData]="foods" class="food-grid" (cdkDropListDropped)="drop($event)">
    <div *ngFor="let food of foods" class="food-item">
    <img src="page_delete.png" (click)="deleteFood()" title="delete" />
    <h4>{{ food.name }}</h4>
    <ul>
    --> bunch of data <--

    </ul>
    </div>
    </div>

    I want to drag the food item and just add the name of the item and it's ID to the Meal item
    I've tried this, but it doesn't work because I can't get past the data mismatch:

    drop(event: CdkDragDrop<Foods[] | Meals[]>) {
    if (event.previousContainer === event.container) {
    moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
    if (event.previousContainer.id === 'cdk-drop-list-foods') {
    const foodItem = event.previousContainer.data[event.previousIndex];
    const mealIndex = event.container.data.findIndex(meal => meal.id === event.container.id);
    if (mealIndex !== -1) {
    this.meals[mealIndex].foods.push(foodItem);
    }
    } else {
    const mealIndex = this.meals.findIndex(meal => meal.id === event.previousContainer.id);
    const foodItem = this.meals[mealIndex].foods[event.previousIndex];
    this.meals[mealIndex].foods.splice(event.previousIndex, 1);
    // Add food back to foods array
    this.foods.push(foodItem);
    }
    }
    }

    export interface Foods {
    name: string,
    calories: number,
    protein: number
    carbs: number,
    potassium: number,
    id: number
    }
    export interface Meals {
    name: string,
    id: string,
    foods: Foods[]
    }


    I really just want to move the Name and ID from Food.

    Continue reading...

Compartilhe esta Página