angular - 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
}
解决方案
不要将值传递给像这样 active="{{newNames[name]}}" 的子组件,而是执行 [active]='newNames[name]
推荐阅读
- c# - 如何在 ASP.NET 和桌面应用程序之间交换数据?
- html - 如何在 IE 中选择选项时删除白色背景
- mysql - 外键格式错误:MySQL
- algorithm - 以最低成本划分为 n 个箱
- java - 如何在 Android 表单中进行过滤后的类似选择选项的下拉菜单?
- linux - ext4 中的项目配额
- python - 如何正确 numpy.nanmean 和 3D 数组上的轴关键字?
- haskell - 并行数字积分器功能比顺序版本慢。为什么?
- mysql - 如何在 Phpmyadmin 中使用 PopSQL
- git - Git:错误:无法读取 MacOSX.sdk 的 SDK 设置