【问题标题】:Angular - Parent with ngFor waits for child to click before moving onto to new item in ngForAngular - 具有 ngFor 的父级等待子级单击,然后再移动到 ngFor 中的新项目
【发布时间】:2021-05-02 14:07:18
【问题描述】:

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

这是父组件代码:

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>

【问题讨论】:

  • 你想让子组件在子元素中的按钮被点击时渲染吗?
  • 我希望找到一种方法来只显示带有按钮的 Curly,一旦单击该按钮,for 循环就会移动到下一个条目,并且只显示带有按钮的 Moe。感谢您的关注。

标签: angular parent-child parent


【解决方案1】:

父 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多