首页 文章

模态 - 无法接近和@Input使用外部组件

提问于
浏览
0

我正在尝试使用 @Input 与组件,但无法弄清楚当我点击打开模态时如何发送变量 . 例如,我有以下模板:

<template #modalContent>
    <my-component-with-content [var1]="val1"></my-component-with-content>
</template>

当我点击打开模态时:

<button type="button" (click)="open(modalContent)" class="btn btn-default">Open</button>

我也对close函数感到困惑 .

我试过了:

<template #modalContent let-close='close'>
    <my-component-with-content></my-component-with-content>
</template>

当我尝试调用 (click) = close("close") 时,在my-component-with-content(html)中我收到以下错误:self.context.close不是函数

所以我的问题是如何在单击打开按钮时传递var1,如何将 close 函数传递给外部组件?

Edit :我正在使用ng-bootstrap modal

1 回答

  • 1

    注意,这是在Angular 2.0.1,ng-bootstrap alpha6中实现的

    您可以通过以下方式将close函数传递给组件:

    <template #modalContent let-c="close"> <my-component [var1]="val1" [close]="c"></my-component> </template>

    这使您可以调用绑定到modalContent的close函数 . 您为var1指定的输入绑定意味着您的输入是从父组件中名为val1的变量设置的,因此不需要在打开时传递,因为您列出的第一个方法应该起作用 .

    import { Component, Input } from "@angular/core";
    
    @Component({
    selector: "my-component",
    template: "<h2>{{var1}}</h2>" +
        "<button (click)='close()'>Close</button>"
    })
    export class MyComponent {
        @Input()
        var1: string;
    
        @Input()
        close: Function;
    }
    

    公开 val1: string = "some thing";

    当我单击按钮打开它时会显示 some thing ,其下方有一个按钮,按下该按钮时将关闭模态模板 .

相关问题