首页 > 解决方案 > Angular - 布尔值在模板中不起作用

问题描述

我在数据绑定和将数据从父组件传递到子组件时遇到问题。有这个值“活动”应该是布尔值,我想根据该值更改按钮的类别。所以有这个父组件将真/假传递给孩子,我什至可以正确打印出这个值(例如

标签),但每当涉及到像“active == true”这样的检查时,它总是给出一个答案,无论 active 变量是什么。有人能帮我吗?=)

父组件.html:

<div class="box">
<div class="columns is-mobile is-centered is-multiline" >
    <div class="column is-half-mobile is-4-tablet" *ngFor = 'let name of names; let i = index' >
        <app-controler [ingredientName]='name' active="{{newNames[name]}}"></app-controler>
    </div>
</div>
</div>

父组件.ts:

export class ControlsComponent implements OnInit {
  ingredients:Pizza
  names = ['tomatoes', 'onions', 'cheese', 'peppers', 'beans', 'corn']
  newNames = {}
  constructor(private foodService:FoodService) { }

  ngOnInit(): void {
    this.ingredients = this.foodService.getIngredients('pizza');
    for (let name of this.names){
      if (this.ingredients[name] == 0){
        this.newNames[name] = false
      } else {
        this.newNames[name] = true
      }
      
    }
}}

子组件 .html:

<button class="button" [ngClass]='{"is-success": active===false }' (click)='ingredientOnClick(ingredientName)'>
    {{ingredientName}} {{active ? 'yes' : 'no'}}
</button>

这个检查 {{active ? 'yes' : 'no'}} 也显示错误的输出

子组件 .ts:

export class ControlerComponent {
  @Input() ingredientName:string
  @Input() active = false

}

标签: angulardata-bindingboolean

解决方案


不要将值传递给像这样 active="{{newNames[name]}}" 的子组件,而是执行 [active]='newNames[name]


推荐阅读