【问题标题】:Angular - boolean doesn't work in templateAngular - 布尔值在模板中不起作用
【发布时间】:2021-07-12 02:26:09
【问题描述】:

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

标签),但每当涉及到像“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

}

【问题讨论】:

  • 不要将值传递给像这样 active="{{newNames[name]}}" 的子组件,而是执行 [active]='newNames[name]' 并检查它是否有效。也尽量不要使用'==='
  • 是的,就是这样。谢谢。那么 [active]= 和 active= 之间究竟有什么区别?
  • [ ] 用于从源到视图的数据绑定。
  • 您可以接受下面的答案,这样就不需要 StackOverflow 社区的进一步答案了。

标签: angular data-binding boolean


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2013-07-22
    • 2013-08-12
    相关资源
    最近更新 更多