【问题标题】:Modal is opening but the value from Inputs is undefined. It happens just with the first opening of modal模态正在打开,但来自 Inputs 的值未定义。它发生在第一次打开模态时
【发布时间】:2020-07-11 22:04:58
【问题描述】:

您好,我有一种带有输入的确认模式:

 @Input('input1') input1: string;
 @Input('input2') input2: boolean;

 constructor(private changeDetectorRef: ChangeDetectorRef) {
 }

 ngOnInit() {
 }

 public openModal(): void {
     console.log(this.input2)
     console.log(this.input1)
     this.confirmationModal.nativeElement.classList.add('open-modal');
 }

当我在订阅方法中打开此模式时的父组件。在这种方法中,我分配的值是这样的:

@ViewChild('confirmationModal') confirmationModal;
input1: string;
input2: boolean;
ngOnInit(): void {    
}

ngOnDestroy(): void {
}

close(project: any) {  
 this.service.close(project).subscribe((success: ModelDto) => {
            this.confirmationModal.openModal();
            this.input2 = success.input2;
            console.log(this.input2)
            this.input1 = 'Some text';
        });
    }

在 html 中我有:

<app-confirmation-modal #confirmationModal
                        [input1]="input1"
                        (sendConfirm)="toggleSettled($event)"
                        (generateReport)="generateReport()"
                        [input2]="input2">
</app-confirmation-modal>

这是我的confirmationModal中的openModal方法:

console.logs 提供的两个仅在第一次打开模态时才给出 undefined。 因此,当我第一次尝试打开模式时,我得到了一个空模式,并且 input1 和 input2 未定义。但是从这一点开始,每次我打开一个模态时,我都会得到应该在模态和console.logs 中存在的值。所以问题只是第一次打开,我不知道是什么原因造成的。

编辑: 我已经对其进行了更多时间的测试,它似乎延迟了 1 次单击。我的意思是 Modal 中显示的值来自一个循环之前的值,而不是实际点击中的值

【问题讨论】:

    标签: html angular modal-dialog frontend


    【解决方案1】:

    好的,我想我知道这里发生了什么。 ngOnInit 太早了,子视图还没有初始化。请尝试 ngAfterViewInit。有关详细信息,请参阅 Angular2 文档中的组件生命周期 Hooks。

    来自文档:

    ngAfterViewinit:在 Angular 创建组件的视图之后。

    【讨论】:

    • 其实我在 ngOnInit 中没有 :) 我已经尝试了我知道的每一个生命周期 Hook 并且第一次打开 modal 总是有问题
    【解决方案2】:

    您可能必须手动触发更改检测。试试下面的

    confirmation-modal.component.ts

    import { Component, Input, Output, ChangeDetectorRef } from '@angular/core';
    
    export class ConfirmationModalComponent  {
      .
      .
      constructor(private _cdr: ChangeDetectorRef) { }
    
      public openModal(): void {
        this._cdr.detectChanges();
        console.log(this.input1)
        console.log(this.input2)
        this.confirmationModal.nativeElement.classList.add('open-modal');
      }
    }
    

    【讨论】:

    • 您能否说明input1input2 是如何定义的?
    • 我的意思是父组件。并将其发布在问题中。注释中没有代码格式。
    • 1.在调用this.confirmationModal.openModal(); 2 之前为输入变量赋值。我不认为添加CSS 类是打开模式的最佳方式。见这里:stackblitz.com/edit/…
    • 1.实际上我也尝试在调用之前分配值,结果总是一样的。第一次打开模态给我 2 undefined。接下来的都不错。关于 2 我没有使用引导模块,整个项目中的其余模式都是这样完成的,所以我认为这不是问题
    • 那我就别无选择了。一开始我真的不明白为什么它们是未定义的。
    猜你喜欢
    • 2017-05-04
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    相关资源
    最近更新 更多