Как передать ID в модал ngx-bootstrap для подтверждения удаления - PullRequest
0 голосов
/ 05 ноября 2018

Я использую Angular 6 и NGX-Bootstrap

У меня есть компонент и служба, которые при посещении страницы извлекают все «местоположения» из моей базы данных mongodb, используя Nodejs и Mongoose.

Я зациклился на результате вызова http get и поместил имя 'location' в таблицу. Справа от таблицы и части цикла заполнения таблицы (ngFor) я добавил кнопку удаления. Я бы хотел, чтобы пользователь щелкнул по кнопке, а затем перед удалением получил приглашение с модальным предупреждением. Моя проблема заключается в передаче идентификатора местоположения модальному, который затем может вызвать функцию удаления и вернуть идентификатор (идентификатор объекта mongodb)

Мне трудно понять, как перемещать эти данные, потому что я считаю, что цикл ngFor содержит только ссылки на идентификатор для этой области, но модал загружается с помощью templateRef, и функция не принимает другую сносную введите в качестве второго параметра.

Любая помощь очень ценится

---- Компонент

import { Component, OnInit, TemplateRef } from '@angular/core';
import { LocationService } from '../services/location.service';
import { Observable } from 'rxjs';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { Location } from '../models/location.model';
import { NgForm } from '@angular/forms';

@Component({
  templateUrl: './location.component.html',
  styleUrls: ['./location.component.css']
})
export class LocationComponent implements OnInit {
  public locations: Location[] = [];
  addLocationForm = false;
  modalRef: BsModalRef;

  constructor(private locationService: LocationService, private modalService: BsModalService) {}

  ngOnInit() {
    this.locationService.loadAll().subscribe(result => {
      this.locations = result;
    });
  }

  showLocationForm() {
    this.addLocationForm = !this.addLocationForm;
  }

  onSaveLocation(form: NgForm) {
    if (form.invalid) {
      return;
    }
    const location = {
      name: form.value.name
    };
    this.locationService.saveLocation(location).subscribe(result => {
      this.ngOnInit();
      this.addLocationForm = !this.addLocationForm;
    });
  }

  deleteLocation(id) {
    this.locationService.deleteLocation(id).subscribe(result => {
      console.log('Deleted location from inside the delete location function', id);
      this.ngOnInit();
    });
  }

  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template, { class: 'modal-sm' });
  }

  confirm(): void {
    this.deleteLocation('10');
    this.modalRef.hide();
  }

  decline(): void {
    this.modalRef.hide();
  }
}

---- Шаблон

    <table class="table table-hover table-bordered">
  <thead class="thead bg-info text-white">
    <tr>
      <th style="width: 85%" scope="col">Locations</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let loc of locations">
      <td>{{ loc.name | titlecase }}</td>
      <td>
        <button class="actionBtn btn btn-warning">
          <i class="fa fa-pencil-square-o"></i>
        </button>
        <button class="btn btn-danger" (click)="openModal(template)">
          <i class="fa fa-times"></i>
        </button>
      </td>
    </tr>
  </tbody>
</table>
<button class="btn btn-info" (click)="showLocationForm()">Add Location</button>




<ng-template #template>
  <div class="modal-header">
    <h4 class="modal-title pull-left">Delete Location</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body text-center">
    <p>Do you really want to delete this location?</p>
    <button type="button" class="btn btn-primary" (click)="decline()">Cancel</button>
    <button type="button" class="btn btn-default" (click)="confirm()">Delete</button>

  </div>
</ng-template>

1 Ответ

0 голосов
/ 11 апреля 2019
import { Component, OnInit, TemplateRef } from '@angular/core';
import { LocationService } from '../services/location.service';
import { Observable } from 'rxjs';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { Location } from '../models/location.model';
import { NgForm } from '@angular/forms';

@Component({
  templateUrl: './location.component.html',
  styleUrls: ['./location.component.css']
})
export class LocationComponent implements OnInit {
  public locations: Location[] = [];
  addLocationForm = false;
  modalRef: BsModalRef;

  constructor(private locationService: LocationService, private modalService: BsModalService) {}

  ngOnInit() {
    this.locationService.loadAll().subscribe(result => {
      this.locations = result;
    });
  }

  showLocationForm() {
    this.addLocationForm = !this.addLocationForm;
  }

  onSaveLocation(form: NgForm) {
    if (form.invalid) {
      return;
    }
    const location = {
      name: form.value.name
    };
    this.locationService.saveLocation(location).subscribe(result => {
      this.ngOnInit();
      this.addLocationForm = !this.addLocationForm;
    });
  }

  deleteLocation(id) {
    this.locationService.deleteLocation(id).subscribe(result => {
      console.log('Deleted location from inside the delete location function', id);
      this.ngOnInit();
    });
  }

  openModal(template: TemplateRef<any>, data) {
    this.locationData = data
    this.modalRef = this.modalService.show(template, this.locationData);
  }

  confirm(data): void {
    this.deleteLocation(data.id);
    this.modalRef.hide();
  }

  decline(): void {
    this.modalRef.hide();
  }
}

Template

   <table class="table table-hover table-bordered">
  <thead class="thead bg-info text-white">
    <tr>
      <th style="width: 85%" scope="col">Locations</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let loc of locations; let index=index">
      <td>{{ loc.name | titlecase }}</td>
      <td>
        <button class="actionBtn btn btn-warning">
          <i class="fa fa-pencil-square-o"></i>
        </button>
        <button class="btn btn-danger" (click)="openModal(template, loc)">
          <i class="fa fa-times"></i>
        </button>
      </td>
    </tr>
  </tbody>
</table>
<button class="btn btn-info" (click)="showLocationForm()">Add Location</button>


<ng-template #template>
  <div class="modal-header">
    <h4 class="modal-title pull-left">Delete Location</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body text-center">
    <p>Do you really want to delete this location {{locationData.name}}?</p>
    <button type="button" class="btn btn-primary" (click)="decline()">Cancel</button>
    <button type="button" class="btn btn-default" (click)="confirm(locationData)">Delete</button>

  </div>
</ng-template>

передать данные, подобные этим, в модель.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...