Angular 4 将数据/参数传递给模态(使用 ngfor)

标签 angular typescript bootstrap-modal ngfor

我是 Angular 4 的新手,我正在使用 ngFor 在数组中显示数据。每个插件都有许多用户和我设法从后端获得的这些用户列表(ID、 Angular 色等)( spring boot 项目)。我想做的是显示这些用户的数量,当用户单击显示数字的按钮时,会弹出一个模式并显示这些用户的详细信息。 所以我遇到的问题是如何将 {{addon.something}} 传递给模态。

       <tbody>
            <tr *ngFor="let addon of addons">
                <td>{{addon.name}}</td>
                <td>{{addon.url}}</td>
                <td>{{addon.location}}</td>
               <td>
                 <button class="btn btn-outline-primary" (click)="open(content,addon)" >{{addon.users.length}}</button>
                 <!--{{addon.users.length}}-->
                </td>

                <td>
                    <a routerLink="/assign_user_to_addon/{{addon.id}}">Add user</a>
                </td>
            </tr>
        </tbody>

我试图将它传递给 (click)="open(content,addon)" ,但它不起作用。

用于处理模态的 Typescript 代码:

 open(content:any,addon:any) {
    this.modalService.open(content).result.then((result) => {

      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  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}`;
    }
  }

将数据/参数传递给模态框的最佳方式是什么?

最佳答案

我知道这是一个非常古老的问题,但我为实现这一目标付出了很多努力。所以写在这里可能会对某人有所帮助。请注意,此答案适用于 Angular 6。

因此,如果您想将任何数据(可以是任何对象,如 Person)传递给 child ,可以像这样完成。

在子组件中,您需要使用 @Input() 注释声明该变量,例如:

  //Required imports
  export class ChildComponent implements OnInit {

  @Input() dataToTakeAsInput: any;

  ngOnInit() {
  }
  constructor() { }
}

现在要从父组件传递此 dataToTakeAsInput,您可以使用 componentInstance,如下面的代码所示:

//Required imports
export class ParentComponent implements OnInit {

  dataPassToChild: any = null;

  constructor(private modalService: NgbModal) { }

  ngOnInit() {

  }
openChilldComponentModel(){

    const modalRef = this.modalService.open(ChildComponent, { size: 'lg',backdrop:false});

    (<ChildComponent>modalRef.componentInstance).dataToTakeAsInput = dataPassToChild;

    modalRef.result.then((result) => {
      console.log(result);
    }).catch( (result) => {
      console.log(result);
    });
  }
}

像这样你可以传递多个对象。

关于Angular 4 将数据/参数传递给模态(使用 ngfor),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48751149/

相关文章:

node.js - NodeJS 中的 Bootstrap 模态窗口

jquery - 要求工具栏阻止 Bootstrap Modal 显示

javascript - 从另一个数组中过滤出一个数组

javascript - TypeScript - 如何使用数组映射到 ES 6 映射?

html - Bootstrap 模态阴影显示在模态上

javascript - Joi - 根据对象数组中的值验证属性

javascript - Angular 2+ 创建 2 种不同情况的切换

带有 ChangeDetectionStrategy.OnPush 的 Angular 单元测试不起作用

angular - owl-carousel 不适用于带有 html 模板的 Angular *ngfor 循环

javascript - 如何在我的 Angular 项目中添加气候时钟小部件