ngx-bootstrap + Angular 12 从另一个组件打开模式

ngx-bootstrap + Angular 12 Open modal from another component

我正在尝试在 Angular.

中创建一个通用的 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) {}
}

<button type="button" class="btn btn-primary" (click)="openModalWithComponent()">Create modal with component</button>

<child-modal #childModal ></child-modal>

但是它说'找不到名称'ModalContentComponent'。

我真的不明白他们从哪里得到的,尽管它似乎对其他人有用。

基本上,您创建一个名为 ModalContentComponent 的新组件 - 只需使用 CLI 即可:

ng generate component /path/modal-content

然后像往常一样导入新创建的 ModalContentComponent 在您的 .ts 代码中引用它的任何地方(例如,您在问题中给出的代码),瞧!

显然,请确保您以通常的方式在模块中声明了 ModalContentComponent(如果您的设置正确,CLI 应该会为您处理)

可选的附加信息:

为了使模式更加可重用,您可能希望模式内容组件中的 HTML 使用内容投影,这将涉及使用支持内容投影的附加组件。

最后我遵循了 this other tutorial 这对我有用。

以下示例用于向数组添加项目:

创建一个简单的组件 ItemList 以显示添加到数组的项目列表。

ng g c itemList

项目-list.component.html

<div>
    <h1> Item List </h1>
    <ul>
    <li *ngFor=”let item of itemList”>{{item}}</li>
    </ul>
    <button type=”button” class=”btn btn-primary”>Add New Item</button>
</div>

项目-list.component.ts

export class ItemListComponent implements OnInit {
  itemList = ["Book","Pen"]
  constructor() { }
  ngOnInit() {
  }
}

让我们创建另一个组件用作模式。

ng g c itemAdd

添加新项目的第二个组件,将来用作模态。此外,我还编写了一个名为 saveToList() 的简单函数,该函数也将在未来实现。现在,我放了一个简单的控制台日志,只是为了在输入字段中显示值。

numberOfItems 将是现有数组中的项目数。

项目-add.component.html

<div class="modal-body">
    <h4>Add Item</h4>
    <form [formGroup]="itemform" (ngSubmit)="saveToList(itemform)">
        <div class="col-md-6">
            <label>Number of Items : </label> {{numberOfItems}}
        </div>
        <div class="col-md-6">
            <label>Item Name</label>
        </div>
        <div class="col-md-6">
            <input type="text" class="form-control" formControlName="name">
            <button class="button mt-1" type="submit">Save</button>
        </div>
    </form>
<div>

项目-add.component.ts

export class ItemAddComponent implements OnInit {
     itemform;
     numberOfItems = 0;
     constructor(private formBuilder: FormBuilder) {
         this.itemform = this.formBuilder.group({
         name: ""
         })
     }

     ngOnInit() {
     }

     saveToList(form) {
        console.log(form.value);
     }
}

添加模态。
让我们更改代码以在单击“添加新项”按钮时以模式打开添加项表单。

项目-list.component.ts

export class ItemListComponent implements OnInit {
 itemList = ["Book","Pen"];
 bsModalRef: BsModalRef;
 constructor(private modalService: BsModalService) { }
 
 ngOnInit() {
 }
 
 openModalWithComponent() {
   this.bsModalRef = this.modalService.show(ItemAddComponent);
   this.bsModalRef.content.closeBtnName = 'Close'; 
 }
}

不要忘记将 ItemAddComponent 添加到 app.module.ts

中的 entryComponents 列表中
providers: [],
entryComponents: [ItemAddComponent],

将值从父级传递到模态。
我们可以简单地使用 initialState 将初始值传递给模态 .

项目-list.component.ts

openModalWithComponent() {
    const initialState = {
        list: [
            "test"
        ]
    };
    this.bsModalRef = this.modalService.show(ItemAddComponent, {initialState});
    this.bsModalRef.content.closeBtnName = 'Close'; 
}

从添加项模式中读取此值。
在模态中初始化一个列表,item-add.component.ts

list: any[] = [];

那么initialState列表可以作为“list[]”访问。
我们正在发送样本数据“test”,它可以作为 list[0] 从 item-add.component.html

访问
<label>Number of Items : </label> {{list[0]}}

认为我们要将项目列表中的对象传递到模式中。

项目-list.component.ts

openModalWithComponent() {
  const initialState = {
    list: [
      {"tag":'Count',"value":this.itemList.length}
    ]
  };
  this.bsModalRef = this.modalService.show(ItemAddComponent, {initialState});
  this.bsModalRef.content.closeBtnName = 'Close'; 
}

--

<label>Number of Items : </label> {{list[0].value}}

将值从模态传递给子项。
让我们看看如何从添加项目表单向项目列表传递一个值。在项目内声明一个 EventEmitter-add.component.ts

public event: EventEmitter<any> = new EventEmitter();

保存项目时发出事件。

triggerEvent(item: string) {
    this.event.emit({ data: item , res:200 });
}

项目-add.component.ts

export class ItemAddComponent implements OnInit {
  itemform;
  numberOfItems = 0;
  list: any[] = [];
  public event: EventEmitter<any> = new EventEmitter();
  constructor(private formBuilder: FormBuilder, public bsModalRef: BsModalRef) {}

  ngOnInit() {
    this.itemform = this.formBuilder.group({
      name: ""
    })
  }

  saveToList(form) {
    this.triggerEvent(form.value.name);
    this.bsModalRef.hide();
  }

  triggerEvent(item: string) {
    this.event.emit({ data: item , res:200 });
  }
}

在 item-list.component.ts 中我们可以订阅事件发射器。

项目-list.component.ts

openModalWithComponent() {
  const initialState = {
    list: [
      {"tag":'Count',"value":this.itemList.length}
    ]
  };
  this.bsModalRef = this.modalService.show(ItemAddComponent, {initialState});
  this.bsModalRef.content.closeBtnName = 'Close';

  this.bsModalRef.content.event.subscribe(res => {
    this.itemList.push(res.data);
  });
}