首页 > 解决方案 > 将参数传递给组件。是否使用括号

问题描述

在 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>    

我错过了什么?

标签: angulartypescript

解决方案


  • 没有括号,该值被视为字符串常量
    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 会将字符串视为常量并使用该字符串初始化目标属性。它不评估字符串!


推荐阅读