【问题标题】:Prevent data bind for child component in ngFor防止 ngFor 中子组件的数据绑定
【发布时间】:2020-07-10 00:01:02
【问题描述】:

我有一个在 ngFor 循环中使用子组件的组件。此子组件具有使用@Input 读取的数据绑定。

我面临的问题是,当我将数据推送到子组件时,子组件的每个实例都会获得相同的值。 有没有办法只为 ngFor 中子组件绑定的特定实例推送数据?

Here is a dummy example I created

当我单击第一个按钮时,我希望它以这种方式工作,只有第一个子组件应该获得值,但第二个应该是空的。

我是 Angular 环境的新手,所以任何帮助都会很棒。

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    pushToChild 将在孩子之间共享,所以我们不要使用它。我能想到的最简单的方法是使用转换为变量声明 (#child) 的子 DOM 元素直接将值传递给子元素,这在循环时是唯一的。

    .ts

    import { Component } from '@angular/core';
    import { ChildComponent } from './child-component/child.component';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      object: { [key: number]: string } = { 2: 'foo', 1: 'bar' };
    
      push(value: any, child: ChildComponent) {
        child.data = value;
      }
    }
    

    .html

    <span>
      <p>Some dummy list</p>
      <div *ngFor="let item of object | keyvalue"
           style="background:gray; margin-top:0.5rem">
        Click button to push value: {{ item.key }} to child
        <button (click)="push(item.key, childRef)">Push</button>
        <child-component #childRef></child-component>
      </div>
    </span>
    

    【讨论】:

    • 你可以摆脱push方法:(click)="child.data = item.key"
    猜你喜欢
    • 1970-01-01
    • 2020-03-08
    • 2016-05-01
    • 2018-11-27
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    相关资源
    最近更新 更多