[英]Angular- When I click on a component, all instances of that component are reinitalized
[英]Angular- How to open a modal component from outside of a button click
我正在使用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>
但單擊此按鈕會拋出錯誤“ TypeError:_co.open不是函數 ”
那么你可以分配參考。
<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>
您不能只在另一個組件中調用方法。
按鈕所在的組件與open()方法的另一個組件的關系是什么?
您可能應該使用EvenEmitter從第一個組件發出按鈕單擊並在另一個組件中訂閱,通過某種共享服務或輸入 - 輸出關系,在組件具有子 - 父關系的情況下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.