首页 > 解决方案 > Angular - 如何以编程方式初始化新组件?

问题描述

我有这个组件(popups.component.ts),我正在尝试在另一个文件(GameManager.ts)中创建它的新实例:

popups.component.ts

import { Component, HostListener, OnInit } from '@angular/core';
import { ITermsAndConditionsPopupData } from '../../services/terms-and-conditions-popup/ITermsAndConditionsPopupData';

@Component({
  selector: 'app-popups',
  templateUrl: './popups.component.html',
  styleUrls: ['./popups.component.css']
})
export class PopupsComponent implements OnInit {
  private _isShown: boolean;
  private _data: ITermsAndConditionsPopupData;
  private styles: {};

  constructor() {
    this._isShown = false;
   }

  ngOnInit(): void {
  }

  public get isShown(): boolean { 
    return this._isShown;
  }

  public open() {
    this._isShown = true;
  }

  public close() {
    this._isShown = false;
  }

  public setData(description: string, title: string = "") {
    this._data = {
      title,
      description,
    };
  }

  public setStyles(styles: { width: string, height: string }) {
    this.styles = styles;
  }

  @HostListener('document:keydown.Esc', ['$event'])
  onEscKeyPress(event: KeyboardEvent) {
    if (!this._isShown) {
      return;
    }
    this.close();
  }
}

popups.component.html

<div *ngIf="_isShown" [class]="true ? 'error-popup-container' : 'terms-and-conditions-popup-container'" [style]="styles">
    <div class="content">
        <div class="title" [innerHTML]="data?.title"></div>
        <div>{{ _isShown }}</div>
        <div class="description" [innerHTML]="data?.description"></div>
    </div>
    <div class="buttons-container">
        <div class="popup-close-button" (click)="close()">
            Close
        </div>
    </div>
</div>

GameManager.ts完整文件(从第 66 行读取)=>点击这里

我正在尝试以这种方式对其进行初始化 - 但它不起作用(弹出窗口未打开)而且我不知道为什么?

  const testPopup = new PopupsComponent();
  testPopup.setData('Here is the description', 'TITLE');
  testPopup.setStyles({ width: '500px', height: '300px' });
  testPopup.open();
  console.log(testPopup);

标签: angularcomponents

解决方案


推荐阅读