Закрытие динамического c модального окна от вставленного в него компонента - PullRequest
0 голосов
/ 10 марта 2020

У меня есть компонент, динамически загружаемый в модальный компонент. Модальный компонент имеет closeModal, который закрывает диалог. Мне нужно вызвать это из механизма remindMeLater компонента Соглашения. Этот компонент вводится в модальный компонент. Как это сделать ?

Диалоговый модуль

@NgModule({
  imports: [CommonModule, FontAwesomeModule],
  declarations: [DialogComponent,  InsertionDirective , AgreementComponent, CustomScrollDirective],
  entryComponents: [DialogComponent, AgreementComponent ] 
})

export class DialogModule {}

Диалоговый компонент

@Component({
  selector: 'app-dialog',
  templateUrl: './dialog.component.html'
})

export class DialogComponent implements AfterViewInit, OnDestroy {
  private readonly _onClose = new Subject<any>();

  public componentRef: ComponentRef<any>;
  public childComponentType: Type<any>;
  public onClose = this._onClose.asObservable();

  // add this:
  @ViewChild(InsertionDirective, { static: false })
  insertionPoint: InsertionDirective;

  constructor(public componentFactoryResolver: ComponentFactoryResolver,
              public cd: ChangeDetectorRef,
              public dialog: DialogRef) {
  }

  ngAfterViewInit() {
    this.loadChildComponent(this.childComponentType);
    this.cd.detectChanges();
  }

  ngOnDestroy() {
    if (this.componentRef) {
      this.componentRef.destroy();
    }
  }

  onOverlayClicked(evt: MouseEvent) {
    // close the dialog
  }

  onDialogClicked(evt: MouseEvent) {
    evt.stopPropagation();
  }

  loadChildComponent(componentType: Type<any>) {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
    const viewContainerRef = this.insertionPoint.viewContainerRef;
    viewContainerRef.clear();
    this.componentRef = viewContainerRef.createComponent(componentFactory);
  }

  closeModal() {
    this.dialog.close();
  }
}

Компонент соглашения

Component({
  selector: 'agreement-component',
  templateUrl: './agreement.component.html'
})

export class AgreementComponent implements OnInit {
  @ViewChild('scroll', { read: ElementRef, static: false }) public scroll: ElementRef<any>;

  myData: any;
  agreementData: any;
  agreementId: number;
  previousSection: number;
  activeBtn: number;
  currentIndex: number;
  hideEverything = false;
  endOfAgreements = false;
  agreementScrollHeight: number;
  agreementAgreed: boolean;
  todaysDate: Date;
  daysUntil: number;
  hoursUntil: number;
  agreementLength: number;
  lastAgreement: boolean;
  currentUser: any;
  dataLength: number;

  constructor(private userService: UserService, public agreementsService: AgreementsService, private msalService: MsalService) {
    this.activeBtn = 0;
    this.previousSection = -1;
    this.hoursUntil = null;
    this.todaysDate = new Date();
    // Load 1st index content in on page load:

    this.currentUser = this.userService.getCurrentUser().id;
  }

  ngOnInit() {
    this.getOutstandingAgreements(this.currentUser);
  }

  checkIfLastAgreement(justUpdated: number) {
    this.agreementLength === justUpdated + 1 ? this.lastAgreement = true : this.lastAgreement = false;
  }

  acceptSection() {

    if (this.lastAgreement) { this.endOfAgreements = true; }

    this.currentIndex = this.activeBtn;
    this.checkIfLastAgreement(this.activeBtn + 1);
    this.activeBtn = this.activeBtn + 1;

    // if (agreementChoice === true) {

    this.update(Accepted);
    // User selected agree so they can view the next agreement
    this.agreementAgreed = true;
    // Set previous section so add agreed indicator
    this.previousSection = this.activeBtn - 1;

    // ONLY call next section if user isn't on the last viewable agreement!
    // tslint:disable-next-line:no-unused-expression
    if (this.activeBtn !== this.agreementLength) {
      this.getNextSectionContent(this.activeBtn);
    }

  }

  declineSection() {
    this.currentIndex = this.activeBtn;
    this.hideEverything = true;
  }

  remindMeLater() {
    this.currentIndex = this.activeBtn;
    this.update(Deferred);
  }

  getNextSectionContent(contentIndex: number) {
    // Get scroll height of agreement
    this.agreementScrollHeight = this.scroll.nativeElement.scrollHeight;

    // Calculate remaining days left on next agreement
    this.calculateRemainingDaysLeft(contentIndex);

    this.agreementData = this.myData[contentIndex].data;
    this.scroll.nativeElement.scrollTop -= this.agreementScrollHeight;
  }

  public getOutstandingAgreements(Id: number) {
    this.agreementsService.getOutstandingAgreements(Id).subscribe((data: AgreementsModel[]) => {
      if (data.length > 0) {
        this.myData = data;
        this.agreementData = this.myData[0].data;
        this.agreementLength = this.myData.length;
        this.calculateRemainingDaysLeft(0);
      }
    });
  }

  calculateRemainingDaysLeft(contentIndex: number) {
    this.hoursUntil = null; // reset this value
    this.daysUntil = differenceInDays(this.myData[contentIndex].reviewWindowExpiry, this.todaysDate);

    if (this.daysUntil < 1) {
      this.hoursUntil = differenceInHours(this.myData[contentIndex].reviewWindowExpiry, this.todaysDate);
      this.daysUntil = null;
    }
  }

  update = (userAgreementStateId: number) => {
    this.agreementsService.updateAgreement(this.myData[this.currentIndex].userAgreementId,
      userAgreementStateId,
      this.currentUser).then(() => {
      });
    return false;
  }

  backToAgreement() {
    this.hideEverything = false;
  }
  confirmDecline() {
    this.update(Declined);
    this.msalService.logout();
  }
}

1 Ответ

0 голосов
/ 10 марта 2020

Вы можете прослушивать динамически созданные компонентные выходы:

componentRef.instance.outputName.subscribe(() => this.closeModal())
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...