Как правильно загрузить и открыть компонент внутри модального диалога в Angular4 - - PullRequest
0 голосов
/ 28 июня 2018

У меня есть компонент с именем NewCustomerComponent, и я хочу загрузить и отобразить его через модальное всплывающее окно на другой странице / компоненте при нажатии кнопки. Я написал соответствующий бит кода [или так кажется]. Но я получаю следующую ошибку -

    this._childInstance.dialogInit is not a function
at ModalDialogComponent.dialogInit (modal-dialog.component.js:65)
at ModalDialogService.openDialog (modal-dialog.service.js:26)
at OrderNewComponent.newCl (order-new.component.ts:85)

Мой код тоже довольно прост в компоненте, где я пытаюсь открыть модальное всплывающее окно. Я просто выложу соответствующие порции -

    import { Component, Inject, ViewContainerRef, ComponentRef } from 
             '@angular/core';
    import { Http, Headers } from '@angular/http';
    import { Router } from '@angular/router';
    import { Observable, Subject } from 'rxjs';
    import 'rxjs/add/operator/map';
    import { CustomerSearchService } from '../../../shared/services/customer- 
       search.service';
    import { ICustomer, Customer, CustomerD } from 
       '../../../shared/models/customer';
    import { ModalDialogModule, ModalDialogService, IModalDialog } from 'ngx- 
      modal-dialog';
    import { NewCustomerComponent } from 
      '../../../components/popups/customer/customer-new.component';


    @Component({
        selector: 'order-new',
        templateUrl: './order-new.component.html' 
    })

    export class OrderNewComponent {

    public reference: ComponentRef<IModalDialog>;

    constructor(private cusService: CustomerSearchService, private http: 
        Http, private modalService: ModalDialogService, private viewRef: 
        ViewContainerRef) {

    }

   ngOnInit(): void {

   }


  ** this is where I am trying to load the newcustomercomponent and open it 
  in the popup. not working.     
  newCl() {
     this.newC = true;
     this.exiC = false;

     this.modalService.openDialog(this.viewRef, {
        title: 'Add New Customer',
        childComponent: NewCustomerComponent
     });
   }

 }

** правок. Добавлен код NewCustomerComponent для справки.

    import { Component, Input, Output, EventEmitter, OnInit, 
       ChangeDetectorRef, Directive, ElementRef, Renderer, AfterViewInit } 
       from '@angular/core';
    import { Router, ActivatedRoute } from '@angular/router';
    import { NgFor } from '@angular/common';
    import { Observable } from 'rxjs/Rx';
    import { BehaviorSubject } from 'rxjs/Rx';
    import { PlatformLocation } from '@angular/common';
    import { Http } from '@angular/http';
    import { ICustomer, Customer } from '../../../shared/models/customer';
    import { UserService } from '../../../shared/services/UserService';
    import { IModalDialog, IModalDialogOptions, IModalDialogButton } from 
         'ngx-modal-dialog';
    @Component({
       selector: 'new-customer',
       templateUrl: './customer-new.component.html'
    })

    export class NewCustomerComponent implements IModalDialog {
       model: Customer = new Customer();
       errors: any;
       submitResponse: any;
       actionButtons: IModalDialogButton[];

       constructor(private userService: UserService, private http: Http) {
                  this.actionButtons = [
                  { text: 'Close', onAction: () => true }
               ];
       }


      ngOnInit() {

      }

      dialogInit(reference: ComponentRef<IModalDialog>, options: 
                       Partial<IModalDialogOptions<any>>) 
      {
                // no processing needed
      }

     createCustomer() {
          this.userService.createCustomer(this.model)
        .take(1)
        .subscribe(
            (response: any) => {
                this.submitResponse = response;

                if (response.success) {
                    console.log('New customer added!');
                }
                else {
                    console.log('Unable to add customer!');
                }
            },
            (errors: any) => this.errors = errors
        );
    return false;
}

     cancelClicked() {

     }

   }

Что я тут не так сделал? Имеет ли это какое-то отношение к ссылке на элемент, которую я добавил в терминах viewRef? Какая часть ошибочна? Как насчет этого дочернего компонента? Требуется ли для этого какая-то конкретная конфигурация / разметка / компонент? Я очень плохо знаком с угловой; Я не уверен, в чем причина.

Пожалуйста, помогите мне исправить этот сценарий. Заранее спасибо,

1 Ответ

0 голосов
/ 28 июня 2018

Можете ли вы убедиться, что NewCustomerComponent реализует интерфейс IModalDialog. Также, если это не так, пожалуйста, поделитесь кодом NewCustomerComponent.

редактирует

Похоже, вы не определили метод dialogInit в NewCustomerComponent, и он не появлялся раньше, поскольку вы не реализовали интерфейс IModalDialog. Я бы попросил вас определить метод dialogInit в классе компонентов, как предложено по ссылке .

...