【问题标题】:Angular 2: Parent-Child Component Property BindingAngular 2:父子组件属性绑定
【发布时间】:2018-02-13 10:18:33
【问题描述】:

如何属性绑定子组件?我想通过其父组件将我的变量 high 变为 false or !this.high 但问题是,孩子正在循环

应用产品

<button class="ui primary small button"(click)="clearVals()">Clear Selected</button>
<app-product-list [dataSource]="data"></app-product-list>


@ViewChild(ProductListComponent) prodList: ProductListComponent;
clearVals() {
    this.selectedOutsourced = this.selectedPrice = 0;
    this.prodList.clear();
    this.selectedArray = [];
}

应用产品列表

<div class="products-cards" *ngFor="let product of dataSource['docs']">
      <app-product-card [product]="product"(highlightEvent)="highlight($event)">
      </app-product-card>
</div>


@ViewChild(ProductCardComponent) prodCard: ProductCardComponent;

应用产品卡片

<div class="list card ui" (click)="highlight()" [class.selected]="high"> </div>


high : boolean = false;
highlight(){
     this.high = !this.high;
}

这是育儿的顺序。最上层是从父到子

【问题讨论】:

  • “孩子被循环”是什么意思?
  • 您是否尝试将事件从孩子传播到父母?
  • *ngFor @Carsten
  • @RahulSingh 实际上还有另一个父级,如果您单击该按钮,它将查看 app-product-list 组件
  • 令人困惑的@Char

标签: angular boolean parent-child angular-components property-binding


【解决方案1】:

这个很有趣,我读了 5 次后才注意到。

你的 div 有一个 *ngFor。 你的孩子在那个 div 里,所以这个孩子会被循环掉。

<div class="products-cards" *ngFor="let product of dataSource['docs']">
          <app-product-card [product]="product"(highlightEvent)="highlight($event)">
          </app-product-card>
    </div>

应该是

    <div class="products-cards" *ngFor="let product of dataSource['docs']">
        </div>
<app-product-card [product]="product"(highlightEvent)="highlight($event)">
              </app-product-card>

然后在你的孩子身上

@Input()
  set product(product: any) {
    highlightF(product);
  }

highlightf(product: any){
  this.hightlight.emit(product);
}

现在在你的父母中:

//Do something to set product.highlight

【讨论】:

    【解决方案2】:

    您需要将子组件中的代码更改为

    app-product-card 子组件 typescript

    import { Component, Input, Output, EventEmitter } from '@angular/core';
    
    @Input() product: any;
    
    @Output() highlightEvent= new EventEmitter();
    
    highlight(){
       this.highlightEvent.emit(somevalue);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-15
      • 1970-01-01
      • 2016-07-21
      • 2017-05-18
      • 2016-05-21
      • 2017-09-20
      • 2019-03-23
      • 2017-08-18
      • 2019-02-05
      相关资源
      最近更新 更多