【问题标题】:Get object after open modal with @Input directive from component使用组件中的@Input 指令打开模态后获取对象
【发布时间】:2020-03-31 09:51:05
【问题描述】:

我想在打开Modal组件时获取对象并获取从组件传递的值。

所以这是我在UserComponent.ts 中打开ModifyuserModalComponent 的方法:

  constructor(
    public dialog: MatDialog
  ) { }

  modifyUser(user: UteUser) {
    console.log(user); //this print correctlry my object
    this.dialog.open(ModifyuserModalComponent, {
      data: user
    });
  }

这是我的 ModifyuserModalComponent ts 代码:

@Component({
  selector: 'app-modifyuser-modal',
  templateUrl: './modifyuser-modal.component.html',
  styleUrls: ['./modifyuser-modal.component.scss'],
})
export class ModifyuserModalComponent implements OnInit {

  @Input() data: any;

  constructor(
    public dialogRef: MatDialogRef<ModifyuserModalComponent>
  ) { 

  }

  ngOnInit() {
    console.log("usergetted: ", this.data);
  }

  closeDialog(){
    this.dialogRef.close();
  }
}

所以当我点击打开对话框时,我的目标是从UserComponent.ts 获取data。 但是当打开ModifyuserComponent 时,我的数据对象是undefined。 我哪里错了?

【问题讨论】:

    标签: angular input components angular7 angular8


    【解决方案1】:
    this.dialog.open(ModifyuserModalComponent, {
      data: user
    }); 
    

    返回一个MatDialogRef,然后你可以访问实例化的组件。

    因此这将起作用:

    const modalRef = this.dialog.open(ModifyuserModalComponent, {
      data: user
    });
    const modal = modalRef.componentInstance
    modal.data... // your code goes here
    

    【讨论】:

      【解决方案2】:

      使用服务和 Observable 共享数据

      import { Injectable } from '@angular/core';
      import { Observable, Subject } from 'rxjs';
      
      @Injectable({ providedIn: 'root' })
      export class MessageService {
          private subject = new Subject<any>();
      
          sendMessage(message: string) {
              this.subject.next({ text: message });
          }
      
          clearMessage() {
              this.subject.next();
          }
      
          getMessage(): Observable<any> {
              return this.subject.asObservable();
          }
      }
      

      在 ModifyuserModalComponent 中订阅以下方法: this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message; });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-03
        • 2016-07-20
        • 1970-01-01
        • 2021-09-05
        • 1970-01-01
        • 1970-01-01
        • 2015-01-09
        • 2021-03-19
        相关资源
        最近更新 更多