我正在尝试引用嵌套在模式内部的元素。在使用@ViewChild时,该模式适用于模式,但不适用于任何嵌套元素。例如:下面代码中的datePicker。这里的工作示例:https://stackblitz.com/edit/angular-s8dtmm-8gqgus(未定义datePicker的第二个控制台)
export class AppComponent {
@ViewChild('content') modal: ElementRef;
@ViewChild('dp') datePicker: ElementRef;
constructor(private modalService: NgbModal) {}
open() {
this.modalService.open(this.modal);
console.log('modal', !!this.modal); // ref to #content
console.log('dp', this.datePicker); // undefined
}
}
模板:
<ng-template #content let-modal>
<input ngbDatepicker #dp="ngbDatepicker">
<button class="calendar" (click)="dp.toggle()">Date picker</button>
</ng-template>
<button(click)="open()">Open modal</button>
答案 0 :(得分:1)
如果您可以修改示例,以使模式内容是一个单独的组件(即基于this example而不是this one),则您应该能够访问以下版本中的datePicker
组件open()
方法。我创建了一个launch-modal.component
,它定义了“打开”按钮,并在打开模式时注销了dp
的值:
launch-modal.component.html
<button class="btn btn-outline-primary" (click)="open()">Open modal</button>
launch-modal.component.ts
import { Component, ElementRef } from '@angular/core';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from './modal.component';
@Component({
selector: 'launch-modal-component',
templateUrl: './launch-modal.component.html'
})
export class LaunchModalComponent {
constructor(private modalService: NgbModal) {}
open() {
const modalRef = this.modalService.open(ModalComponent);
console.log('dp', modalRef.componentInstance.datePicker);
}
}
然后,我定义了一个modal.component.ts
,它定义了模式内容(基于您问题中的app.module.html
,并为datePicker定义了ViewChild
):
modal.component.ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'modal-component',
template: `
<button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
<input ngbDatepicker #dp="ngbDatepicker">
<button class="btn btn-outline-primary calendar" (click)="dp.toggle()" type="button">Date picker</button>
`
})
export class ModalComponent {
@ViewChild('dp') datePicker: ElementRef;
constructor(public activeModal: NgbActiveModal) {}
}
打开模式时控制台的输出为:
有关有效的演示,请参见this Stackblitz。