练习Angular 2时遭遇"Bindings cannot contain assignments"错误求助
解决Angular的"Bindings cannot contain assignments"错误
嘿,我来帮你搞定这个问题!首先,这个错误提示通常意味着Angular在解析模板的时候,要么遇到了绑定表达式里的赋值操作(比如[all]="total = 10"这种不允许的写法),要么就是模板本身有语法混乱导致解析出错。
看你贴的代码,我一眼就发现了问题:你重复写了一遍<app-employeecount的起始标签!原代码开头部分是:
<app-employeecount [all]= "gettotalemployeescount()" <app-employeecount [all]= "gettotalemployeescount()" ...>
第一个<app-employeecount标签还没闭合,你又写了一个新的起始标签,这直接把Angular的模板解析器搞懵了,它会误把后面的内容当成第一个绑定表达式的一部分,最后就抛出了“绑定不能包含赋值”的错误。
修正后的代码
把重复的那个起始标签删掉,确保组件标签只写一次,同时把属性绑定格式化得更清晰(方便排查问题):
<app-employeecount [all]="gettotalemployeescount()" [male]="gettotalmaleemployeescount()" [female]="gettotalfemaleemployeescount()" (onEmployeeCountRadioButtonChange)="onEmployeeCountRadioButtonChange($event)" ></app-employeecount> <table> <thead> <tr> <th>id</th> <th>name</th> <th>Gender</th> <th>mobile</th> <th>Salary</th> <!-- 这里你原来的内容被截断了,记得把后续的表格标签都正确闭合哦 --> </tr> </thead> <!-- 补充表格主体内容 --> </table>
额外注意事项
- 一定要确保所有HTML标签都正确打开和闭合,避免嵌套或重复起始标签的情况
- 绑定表达式里只能写返回值的逻辑,不能包含赋值操作(比如
=、+=这类都不允许出现在[]或()的绑定里) - 另外提个小建议:Angular里的方法名通常用小驼峰命名法(比如
getTotalEmployeesCount而不是gettotalemployeescount),虽然这不是导致错误的原因,但遵循规范能让代码更易读~
内容的提问来源于stack exchange,提问作者johnny
相关产品推荐
相关产品推荐

