【发布时间】:2020-05-09 09:38:36
【问题描述】:
我有一个 Angular 组件类,在 openModal() 方法中我无法访问 @ViewChild content 属性,但很奇怪,因为 static:true 甚至在 ngOnInit() 和 @ 内部都没有这样的问题987654325@。我已经完成了功课,所以如果我将this.modalService.open(this.content) 行放在这些回调中,一切都可以正常工作,但是如果openModal() 中的行打开时没有内容(当然是ja)。我已经对气候变化做出了重大贡献:
import {AfterViewInit, Component, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {NgbModalConfig, NgbModal} from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-modal-auto-shown',
templateUrl: './modal.component.html',
providers: [NgbModalConfig, NgbModal]
})
export class ModalComponent implements OnInit, AfterViewInit {
@ViewChild('content', {static: true}) private content: any;
private test = 'test_string';
constructor(config: NgbModalConfig, private modalService: NgbModal) {
config.backdrop = 'static';
config.keyboard = false;
}
ngOnInit(): void {
console.log('oninit this:', this);
console.log('oninit this.test:', this.test);
console.log('oninit this.content:', this.content);
}
ngAfterViewInit() {
console.log('afterviewinit this:', this);
console.log('afterviewinit this.test:', this.test);
console.log('afterviewinit this.content:', this.content);
}
openModal(that = this) {
console.log('openmodal this:', this);
console.log('openmodal this.test:', this.test);
console.log('openmodal this.content:', this.content);
console.log('openmodal this:', that);
console.log('openmodal that.test:', that.test);
console.log('openmodal that.content:', that.content);
console.log('openmodal that === this:', that === this);
this.modalService.open(this.content);
that.modalService.open(that.content);
}
}
我在这里转储控制台:
oninit this: ModalComponent {modalService: NgbModal, test: "test_string", content: TemplateRef_}
oninit this.test: test_string
oninit this.content: TemplateRef_ {_parentView: {…}, _def: {…}}
afterviewinit this: ModalComponent {modalService: NgbModal, test: "test_string", content: TemplateRef_}
afterviewinit this.test: test_string
afterviewinit this.content: TemplateRef_ {_parentView: {…}, _def: {…}}
openmodal this: ModalComponent {modalService: NgbModal, test: "test_string"}
openmodal this.test: test_string
openmodal this.content: undefined
openmodal this: ModalComponent {modalService: NgbModal, test: "test_string"}
openmodal that.test: test_string
openmodal that.content: undefined
openmodal that === this: true
test 属性在之后就幸福地生活了,它可以从所有方法访问,但是,@ChildView 属性不是,这与上下文变量this 无关(??)。引擎盖下是什么守护进程?
【问题讨论】:
-
兄弟,当您打印在代码中使用过
that.content的内容时,请从openModal()中删除that = this,最好在不使用that的情况下使用它,我猜是它的引用问题 -
不幸的是,没有
that的this是相同的行为,that是为了证明全局和本地this仍然没有content属性。但是以某种方式同意“那个”:)
标签: angular class components viewchild