A Crowe
A Crowe

Reputation: 61

Angular - Parent with ngFor waits for child to click before moving onto to new item in ngFor

My question is how to force the following item in the list to wait for the child button to be clicked. I won't include all the mistrials that I have tried......

This is the parent component code:

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 {
  }

}

This is the parent html code:

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

This is the child typescript code:

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`);
  }

}

This is the child html code:

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

</div>

Upvotes: 0

Views: 600

Answers (1)

user6749601
user6749601

Reputation:

Parent HTML

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

Parent TS

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

Child TS

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

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

Child HTML

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

Upvotes: 1

Related Questions