首页 > 解决方案 > Angular - 具有 ngFor 的父级等待子级单击,然后再移动到 ngFor 中的新项目

问题描述

我的问题是如何强制列表中的以下项目等待子按钮被点击。我不会包括我尝试过的所有错误审判......

这是父组件代码:

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  mockData = ['Curly', 'Moe', 'Larry', 'Shemp'];

  constructor() {
  }

  ngOnInit(): void {
  }

}

这是父 html 代码:

<app-child *ngFor="let name of mockData" [name] = name></app-child>

这是子打字稿代码:

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() name: string;

  constructor() {
  }

  ngOnInit(): void {
  }

  onClick(): void {
    console.log(`${this.name} has been clicked`);
  }

}

这是子html代码:

<div>
  <p>{{name}}</p>
  <button (click) = onClick()> Wait for Me to Click</button>

</div>

标签: angularparent-childparent

解决方案


父 HTML

<app-child *ngFor="let name of mockData" [name]=name (childClicked)="onChildClicked($event)"></app-child>

家长 TS

onChildClicked(name: string): void {
    console.log('child ' + name + ' was clicked.');
}

儿童 TS

@Output() childClicked: EventEmitter<string> = new EventEmitter<string>();

onClick(): void {
    this.childClicked.emit(this.name);
}

子 HTML

<div>
  <p>{{name}}</p>
      <button (click)="onClick()">Wait for Me to Click</button>
</div>

推荐阅读