angular - 将参数传递给组件。是否使用括号
问题描述
在 Angular 6 中有以下组件:
export class HeaderComponent implements OnInit {
@Input() type: string;
constructor() { }
ngOnInit() {
}
组件的 HTML 如下:
<h1>Title</h1>
<p *ngIf="type=='admin'">Admin Message</p>
我使用的组件如下:
<header [type]="admin"></header>
除非我删除类型周围的括号,否则该消息不会显示:
<header type="admin"></header>
我错过了什么?
解决方案
- 没有括号,该值被视为字符串常量
prop1="val1" // the string "val1" is assigned to prop1
- 使用括号,值是一个被评估的表达式
[prop1]="val1" // the value of the class property val1 is assigned to prop1
[prop1]="val1()" // the value returned by the method val1() is assigned to prop1
[prop1]="'val1'" // the string "val1" is assigned to prop1
[prop1]="condition ? val1() : 'val2'" // the result is assigned to prop1
来自 Angular文档:
记住括号
括号告诉 Angular 评估模板表达式。如果省略括号,Angular 会将字符串视为常量并使用该字符串初始化目标属性。它不评估字符串!
推荐阅读
- amazon-web-services - AWS S3 存储复制功能
- excel - 访问条件格式单元格的颜色值(或识别条件格式单元格)
- spring-webflux - Spring 5 WebFlux 使用 WebSocket 的反应式服务器推送通知
- php - 用户偶尔会被注销(仅在 Chrome 中发生)
- html - 为什么我的引导时间线样式不正确?
- amazon-web-services - Athena AWS - 如何将二进制转换为 Bigint
- javascript - 从 GitHub 存储库更新谷歌表格?
- apache-spark - Apache Spark 按 DF 分组,将值收集到列表中,然后按列表分组
- python - AttributeError:模块“asyncio”在 Python 3.6.10 和 Spyder 4.1 中没有属性“WindowsSelectorEventLoopPolicy”
- asp.net-core - 如何让 Gitlab CI 支持 Asp.net Core 3.1?