ngx-bootstrap如何从另一个组件打开模态?

der*_*zay 8 twitter-bootstrap ngx-bootstrap angular

我想要做的是从另一个组件打开一个模态,但是TypeError: Cannot create property 'validator' on string 'test1'component1.html加载因为childModal包含时我不断收到此错误.如何摆脱这些错误并正确实施?

component1.html

<button type="button" class="btn btn-outline-primary btn-lg" (click)="modal.showModal()">Test
......
<child-modal #childModal ></child-modal>
Run Code Online (Sandbox Code Playgroud)

component1.ts

 @ViewChild('childModal') childModal: ModalComponent;
Run Code Online (Sandbox Code Playgroud)

modal.html

<div bsModal #childModal="bs-modal" class="modal fade" tabindex="-1" role="dialog>
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
          <input type="text" formControl="test1">
          <input type="text" formControl="test2">
          </div>
     </div>
</div>   
Run Code Online (Sandbox Code Playgroud)

modal.component.ts

constructor(private modalService: BsModalService) {
    this.form = new FormGroup({
      'test':                     new FormControl(),
      'test2':                    new FormControl()
      }) 
 }
Run Code Online (Sandbox Code Playgroud)

Fra*_*rzi 12

如果您尝试从另一个组件打开模态组件,那么这是使用ngx-bootstrap执行此操作的正确方法:

import { Component } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';

/* This is the Component from which we open the Modal Component */
@Component({
  selector: 'my-component',
  templateUrl: './service-component.html'
})
export class MyComponent {
  bsModalRef: BsModalRef;
  constructor(private modalService: BsModalService) {}

  public openModalWithComponent() {
    /* this is how we open a Modal Component from another component */
    this.bsModalRef = this.modalService.show(ModalContentComponent);
  }
}

/* This is the Modal Component */
@Component({
  selector: 'child-modal',
  template: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">Title</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">Close</button>
    </div>
  `
})
export class ChildModalComponent {
  constructor(public bsModalRef: BsModalRef) {}
}
Run Code Online (Sandbox Code Playgroud)

调用模态的Component的模板:

<button type="button" class="btn btn-primary" (click)="openModalWithComponent()">Create modal with component</button>
Run Code Online (Sandbox Code Playgroud)

所以,你应该包括模态分量在这样的模板:

 <child-modal #childModal ></child-modal>
Run Code Online (Sandbox Code Playgroud)

官方文件:

https://valor-software.com/ngx-bootstrap/#/modals#service-component

  • 好吧我明白了.我不得不在子组件中取出对`bsmodal`的引用.现在的问题是,在取出`modal.html`的第一行后,模态现在打开为小而不是大.BTW谢谢你的帮助! (3认同)