简体   繁体   English

Angular - boolean 在模板中不起作用

[英]Angular - boolean doesn't work in template

I have a problem with data binding and passing data from parent to child component.我在数据绑定和将数据从父组件传递到子组件时遇到问题。 There is this value 'active' which should be boolean and I would like to change a class of a button depending on that value.有这个值“活动”应该是 boolean,我想根据该值更改按钮的 class。 So there is this parent component which passes true/false to the child, than I can even print out this value properly (eg in所以有这个父组件将真/假传递给孩子,我什至可以正确打印出这个值(例如

tags) but whenever it comes to a check like 'active == true' it always gives one answer, no matter what variable active is.标签),但每当涉及到像“active == true”这样的检查时,它总是给出一个答案,无论 active 是什么变量。 Can someone help me?有人能帮我吗? =) =)

Parent component.html:父组件.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>

Parent component.ts:父组件.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
      }
      
    }
}}

Child component.html:子组件.html:

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

this check {{active?这个检查{{活动? 'yes': 'no'}} also shows wrong output 'yes': 'no'}} 也显示错误 output

Child component.ts:子组件.ts:

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

}

Instead of passing value to child component like this active="{{newNames[name]}}", do [active]='newNames[name]不要将值传递给像这样 active="{{newNames[name]}}" 的子组件,而是执行 [active]='newNames[name]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM