我试图在一个页面上多次使用bootstrap popup组件作为嵌套组件。此弹出组件采用不同的值@Input()
。问题是页面上的每个弹出窗口都与上一个弹出窗口具有相同的值。那么,我如何获得同一嵌套组件的多个实例呢?
这是父组件:
@Component({
selector: 'my-parent',
templateUrl: 'app/components/parent/parent.component.html',
directives: [PopupDirective]
})
export class ParentComponent {
private doSomething() {
// do something
}
}
这是我父组件的html:
<button class="btn btn-success"
(click)="popup1.show()">Call Popup 1</button>
<button class="btn btn-success"
(click)="popup2.show()">Call Popup 2</button>
<my-popup #popup1
[id]="1"
[title]="Popup 1"
[body]="This is my test popup 1"
(confirmation)="doSomething()"></my-popup>
<my-popup #popup2
[id]="2"
[title]="Popup 2"
[body]="This is my test popup 2"
(confirmation)="doSomething()"></my-popup>
这是弹出组件:
@Component({
selector: 'my-popup',
templateUrl: 'app/directives/popup/popup.directive.html'
})
export class PopupDirective {
@Input() id: string;
@Input() title: string;
@Input() body: any;
@Output() confirmation: EventEmitter<string> = new EventEmitter<string>();
private triggerPopup: string;
constructor() {
this.triggerPopup = "triggerPopup";
}
confirm() {
this.confirmation.emit('Click from nested component');
}
show() {
document.getElementById(this.triggerPopup).click();
}
}
最后我的弹出窗口的HTML代码
<a id="{{ triggerPopup }}"
href="#popup{{ id }}"
data-toggle="modal"
[hidden]="true"></a>
<div class="modal fade" id="popup{{ id }}" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>{{ title }}</h4>
</div>
<div class="modal-body">
<div>{{ body }}</div>
<div style="clear: both;"></div>
</div>
<div class="modal-footer">
<a class="bin ban-default"
data-dismiss="modal">
Close</a>
<a class="bin ban-success"
data-dismiss="modal"
(click)="confirm()">
Confirm</a>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
您为每个元素分配相同的ID
constructor() {
this.triggerPopup = "triggerPopup";
}
因此
document.getElementById(this.triggerPopup).click();
始终找到第一个因为它搜索整个页面并且不关心组件边界。
我建议使用模板变量,而@ViewChild()
代替
<a #triggerPopup"
export class PopupDirective {
@ViewChild('triggerPopup') triggerPopup:ElementRef;
show() {
this.triggerPopup.nativeElement.click();
}