4

这是一个更大的项目的一部分,我试图通过这个例子来简化它。我使用 PrimeNg 巴比伦主题。我有一个父组件,它有一个 for 循环,它为每次迭代生成一个按钮和一个带有对话框的子组件。单击此按钮会激活 PrimeNg 对话框。但是由于它是一个按钮和对话框的循环,因此单击这些按钮中的任何一个都会打开每个对话框。(共 3 个)。问题是我不知道如何在单击按钮时定位,只有它是从父组件到子组件的相关对话框,而不是所有按钮。我是 Angular 的新手。有人可以帮忙吗?app.component.html 父组件的代码是:

  <div *ngFor="let item of items; let i = index">
    <button type="button" (click)="showDialog(i)" pButton icon="pi pi-info-circle" label="Show"></button>
    <app-child (notify)="parentListener($event)"></app-child>
  </div>
</div>

app.component.ts 的代码是:


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  display = false;
  items = [
    {1: 1}, {2: 2}, {3: 3}
  ];

  showDialog() {
    this.display = true;
  }

  parentListener(data) {
    this.display = data;
  }
}

child.component.html 的代码是:

<p-dialog header="Godfather I" [(visible)]="display" [modal]="true" [responsive]="true" [style]="{width: '350px', minWidth: '200px'}" [minY]="70"
          [maximizable]="true" [baseZIndex]="10000">
  <p>The story begins as Don Vito Corleone, the head of a New York Mafia family, oversees his daughter's wedding.
    His beloved son Michael has just come home from the war, but does not intend to become part of his father's business.
    Through Michael's life the nature of the family business becomes clear. The business of the family is just like the head of the family,
    kind and benevolent to those who give respect,
    but given to ruthless violence whenever anything stands against the good of the family.</p>
  <p-footer>
    <button type="button" pButton icon="pi pi-check" (click)="display=false" label="Yes"></button>
    <button type="button" pButton icon="pi pi-close" (click)="returningDataToParent()" label="No" class="ui-button-secondary"></button>
  </p-footer>
</p-dialog>

child.component.ts 的代码是:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input ()
  display: boolean;
@Output ()
notify: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor() { }

  ngOnInit() {

  }

  returningDataToParent() {
    this.notify.emit(false);
  }
}
4

0 回答 0