【问题标题】:Angular 5 - Can't Pass Data to ModalAngular 5 - 无法将数据传递给模态
【发布时间】:2018-08-05 23:07:55
【问题描述】:

对我真正想做的事情的简短总结。
如果我点击英雄表。我需要将点击的行中的英雄数据传递给 Modal。

我读到有两种方法可以将数据放入模态。 (NGMODAL) 使用@Input 和@Output 或通过共享服务。 但我使用哪种方式并不重要。模式总是在数据传递之前打开(并获取数据)。

我只是有一个表格,其中显示了我所有的英雄。

单击表格行中的删除按钮时,我不想打开模式并传递表格行中的数据。 (我想传递整个英雄,但与传递英雄的名字应该没有区别)。

之后我想展示。 你真的要删除有名字的英雄吗...? [取消]、[是,删除]。点击是,删除按钮我要删除英雄。

现在连想删除的英雄名字都显示不出来

我希望任何人都可以告诉我我能做什么以及如何做。

谢谢。

这是我的代码:

显示我的英雄:hero.component.html

<div class="container">
    <h2>Heroes</h2>
    <input type="text" placeholder="Suchbegriff eingeben" class="form-control has-float-label" [(ngModel)]="filter" >
    <br>
    <div *ngIf="heroes">
      <table class="heroes table table-hover table table-striped">
          <thead>
            <tr>
              <th>Name</th>
              <th>Delete</th>
            </tr>
          </thead>
          <tbody>
              <tr *ngFor="let hero of heroes | filter:filter:'name':'name'">                  
              <td>{{hero.name}}</td>

// 我可以使用 (click)="pusHero(hero)" 并在战后打开模式。比我通过输入获得正确的数据。但是当我首先点击打开模式时没有数据,或者之前点击的行中的数据

       <td>
            <ngbd-modal-component (click)="selectRow(hero) [(delhero)]="delhero""></ngbd-modal-component>  </td>
      </tbody>
    </table>
  </div>
</div>

heroes.component.ts

import { Component, OnInit, ViewEncapsulation , Input , EventEmitter} from '@angular/core';
import { Hero } from '../../model/hero';
import { HeroService } from '../hero.service';
import { CommonModule } from '@angular/common';
import { Observable } from 'rxjs/Observable';
import { Response } from '@angular/http/src/static_response';
// For use of map
import 'rxjs/Rx';
// Für Pipe und Suche in Liste
import { Pipe, PipeTransform } from '@angular/core';
import { FilterPipe } from '../../pipes/filter.pipe';

// Component Decorator imported from Component
@Component({
  // Unique Selector
  selector: 'app-hero',
  // URL of Template
  templateUrl: './hero.component.html',
  // URL of stylesheet
  styleUrls: ['./hero.component.css']
  // encapsulation: ViewEncapsulation.None
})
export class HeroesComponent implements OnInit {
  heroes: Observable<Hero[]>;
  hero: Hero;
  filter = '';

  // Is Input for Child Component. In this case modal
  delhero: Hero;

  constructor(
    private heroService: HeroService,
    // Modal Service
    // private modalService: NgbModal,
    // private ngbdModalComponent: NgbdModalComponent,
    // private ngbdModalContent: NgbdModalContent,
    ) {
    // this.searchableList = ['name','age']  
   }


  selectRow(hero): void {
    console.log("Select the tables data");  
    console.log(hero);
    this.heroService.selectRow(hero);
  }
}

英雄服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import { Hero } from '../model/hero';
import { MessageService } from '../message.service';
import { Response } from '@angular/http/src/static_response';
// For use of map
import 'rxjs/Rx';
import { headersToString } from 'selenium-webdriver/http';

const httpOptions = {
  headers: new HttpHeaders(
    { 
      'Content-Type': 'application/json'
    }
  )
};

@Injectable()
export class HeroService {

  private hero: Hero;
  constructor(private http: HttpClient, private messageService: MessageService) { }


  selectRow(input){
    this.hero = input;
  }

  getRow(){
    console.log(this.hero);
    return this.hero;
  }
}

我的模态

modal.component.html

<button class="btn btn-danger btn-xs more" (click)="open()"> <span class="fa fa-trash"></span></button>

modal.component.ts

import { Component, Input, EventEmitter, SimpleChange, Output, OnInit } from '@angular/core';
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { NgbdModalContent } from './modal.content.component';
import { Hero } from '../../model/hero';
import { HeroService } from '../../hero/hero.service';

// Modal Component
@Component({
  selector: 'ngbd-modal-component',
  templateUrl: './modal.component.html'
})

export class NgbdModalComponent {
  // @Input() delhero: Hero;
  // hero: Hero;
  // @Output() getDeleteHero = new EventEmitter();
  name = '';
  constructor(private modalService: NgbModal,
  private heroService: HeroService) {}
  ngOnInit(){
    // this.open();
    // console.log(this.delhero);
  }
  open() {
    var name = this.heroService.getRow();
    // this.getDeleteHero.emit();
    console.log("Modal Component hero");
    // console.log(this.delhero);
    this.name = this.heroService.getRow().name;
    const modalRef = this.modalService.open(NgbdModalContent);
    modalRef.componentInstance.name = name;
  }
  delete(){
    console.log("Delete Hero through Hero Service");
  }
}

modal.content.component.html

<div class="modal-header ">
        <h4 class="modal-title">Delete Hero?</h4>
        <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Delete Hero with Name: {{name}}?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="activeModal.close('Close click')">No, do not delete</button>
        <button type="button" class="btn btn-primary">Ja, löschen</button>
      </div>

modal.content.component.ts

import { Component, Input, EventEmitter } from '@angular/core';
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { HeroService } from '../../hero/hero.service';
import { Hero } from '../../model/hero';
// Modal Content
@Component({
  selector: 'ngbd-modal-content',
  templateUrl: './modal.content.component.html'
//   styleUrls: ['./modal.content.component.css']
})
export class NgbdModalContent {
//   @Input() Hero;
name = "";
  constructor(
      public activeModal: NgbActiveModal,
      privateheroService: HeroService
    ) {}

    ngOnInit() {
        //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
        //Add 'implements OnInit' to the class.
        console.log("NG On Init ModalsContent");
        this.name = this.heroService.getRow().name;
        console.log(this.name);

    }
}

【问题讨论】:

    标签: modal-dialog angular5 ng-bootstrap pass-data


    【解决方案1】:

    不确定这是否有帮助,但我在遇到同样的问题后发现了这一点。 我最终得到了工作代码。抱歉,这不是您的代码,但我在遵循它时遇到了麻烦。我必须设置一个变量并通过点击代码将其传递:

        HTML:
    
    <ng-template #content let-c="close" let-d="dismiss">
      <div class="modal-header">
        <h4 class="modal-title">Option Entry</h4>
        <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label class="control-form-label" for="optDescription">Description:</label>
            <input type="text" class="form-control" name="description" ngModel id="optDescription" [(ngModel)]="editOption">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Update</button>
      </div>
    </ng-template>
    
    <div *ngIf='optionList && optionList.length'>
      <div *ngFor='let opt of optionList'>
    
        <ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-0" class="accordianheading">
          <ngb-panel>
            <ng-template ngbPanelTitle>
              <span>{{opt.description}}</span>
              <button class='btn btn-sm btn-outline-primary btnline pull-right' (click)='$event.preventDefault(); $event.stopPropagation(); editItem(content, opt)'>Edit</button>
            </ng-template>
            <ng-template ngbPanelContent>
              <js-option-lists [OptionListID]=opt.id></js-option-lists>
            </ng-template>
          </ngb-panel>
        </ngb-accordion>
    
      </div>
    </div>
    

    和:

    .ts 文件

    import { Component, OnInit, Input } from '@angular/core';
    import { IOptionListHeader } from '../dtos/option-list-header';
    import { OptionListService } from '../services/felixApi/option-list.service';
    import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
    import { NgModel, NgForm } from '@angular/forms';
    
    @Component({
      selector: 'js-option-lists',
      templateUrl: './option-lists.component.html',
      styleUrls: ['./option-lists.component.css']
    })
    export class OptionListsComponent implements OnInit {
      @Input() OptionListID: number;
      errorMessage: any;
      optionList: IOptionListHeader[] = [];
      updatedOption: any;
      closeResult: string;
      editOption = '';
    
      constructor(private _optionListService: OptionListService, private modalService: NgbModal) { }
    
      // for now read in all options but will need to read by level
      ngOnInit() {
        this.getChildren(this.OptionListID);
      }
    
      getChildren (id) {
        this._optionListService.getOptionListChildren(id)
        .subscribe(
          optionList => {
            this.optionList = optionList;
          },
          error => this.errorMessage = <any>error);
      }
    
      // Patch change
      patchOrderNo(updatedOption: any) {
         this._optionListService.updateOption(updatedOption).subscribe(
            res => {
              this.getChildren(this.OptionListID);
            },
            err => {
              console.log('error code ' + err.status);
            }
          );
      }
    
      editItem(content, opt: IOptionListHeader) {
        this.editOption = opt.description;
        this.modalService.open(content).result.then((result) => {
          this.closeResult = `Closed with: ${result}`;
          this.updatedOption = { id: opt.id, description: this.editOption };
          this.patchOrderNo(this.updatedOption);
        }, (reason) => {
          this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
          console.log('cancelled');
        });
      }
    
      private getDismissReason(reason: any): string {
        if (reason === ModalDismissReasons.ESC) {
          return 'by pressing ESC';
        } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
          return 'by clicking on a backdrop';
        } else {
          return  `with: ${reason}`;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-18
      • 2021-06-17
      • 2017-06-15
      • 2018-10-03
      • 1970-01-01
      • 2018-08-30
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多