首页 > 解决方案 > 不能在父级的 [ngClass] 逻辑中使用子级输入值

问题描述

我正在尝试将用户输入值从我的input直通传递给父级,并使用该值来确定要在我的<li *ngFor...元素中突出显示的行。

我实际上可以成功地传递值,所以看起来,因为我设置了一个console.log来捕获子组件首先发出的内容,然后是父组件捕获的内容,但我只是无法通过我的[ngClass]逻辑看到它部分...

如果我硬编码要突出显示的行的值,则逻辑确实可以正常工作,但是当然,我想以编程方式执行此操作。

父组件.ts

  rowId: number;

  childToParent(val){
    console.log('received from child: ' + val);
    this.rowId = val;
  }

父组件.html

<app-child (childToParent)="childToParent($event)"></app-child>
<li *ngFor="let item of items" attr.id="item-{{item.id}}" [ngClass]="{'active': item.id === rowId}">
  <div class="item">
   ...
</li>

child.component.ts

@Output() childToParent = new EventEmitter<String>();

  sendToParent(id){
    console.log('sending to parent: ' + id)

    this.childToParent.emit(id);
  }

child.component.html

<input [(ngModel)]="val" (input)="sendToParent(val)"/>

堆栈闪电战

标签: javascripthtmlangulartypescripteventemitter

解决方案


你确定 item.id 和 rowId 都是数字类型吗?您可以将“===”更改为“==”,它适用于字符串和数字。


推荐阅读