我正在使用ng bootstrap,我有一个名为Modal Component的组件,我将动态传递模态内容。以下是我写的代码:
这是模板文件:
<div class="modal-header">
<h4 class="modal-title">Modal title</h4>
<button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>
</div>
<hr>
以下是组件文件:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-modaltest',
templateUrl: './modaltest.component.html',
styleUrls: ['./modaltest.component.css']
})
export class ModaltestComponent implements OnInit {
closeResult: string;
constructor(private modalService: NgbModal) { }
open(content) {
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}`;
}
}
ngOnInit() {
}
}
我无法在按钮单击时打开此模式,其中按钮在另一个模板文件如下所示的组件中定义:
<button class="btn btn-lg btn-outline-primary" (click)="open(content)" >Launchss demo modal</button>
<app-modaltest ></app-modaltest>
但点击此按钮会抛出错误&#34; TypeError:_co.open不是函数&#34;
答案 0 :(得分:2)
如果你指定一个参考,你可以。
<button class="btn btn-lg btn-outline-primary" (click)="myRef.myMethod()" >Launchss demo modal</button>
<app-modaltest #myRef ></app-modaltest>
但不是来自组件代码,除非您将该引用传递给方法
<button class="btn btn-lg btn-outline-primary" (click)="localMethod(myRef)" >Launchss demo modal</button>
<app-modaltest #myRef ></app-modaltest>
答案 1 :(得分:1)
您无法在另一个组件中调用方法。
按钮所在的组件与使用open()方法的另一个组件的关系是什么?
您可能应该使用EvenEmitter从第一个组件发出按钮单击并在另一个组件中订阅,或者通过某种共享服务或输入 - 输出关系订阅组件具有子父关系。