Angular 2: 属性 带括号和不带括号的区别?

Angular 2: Difference between property binding with and without brackets?

我注意到可以 属性 绑定不带括号的东西。有什么区别?

打字稿:

import { Component, Input } from '@angular/core';

@Component( {
    selector: 'my-comp',
    templateUrl: `
    input is {{foo}}
  `

})
export class myComponent {
    @Input() public foo: string;

    constructor() { }
    }

HTML:

案例一

<my-comp [foo]="bar"></my-comp>

案例二

<my-comp foo="bar"></my-comp>

在某些情况下,我们需要像这样动态添加 html 属性,例如 json 来自 api 请求

案例 1[] 称为 属性 绑定

<my-comp [foo]="data.bar"></my-comp>

情况 2 {{ }} 称为插值

<my-comp foo="{{data.bar}}"></my-comp>

案例 3 条件处理

<my-comp [attr.foo]="data.bar ? true : false"></my-comp>

{{ }} 称为插值,[] 称为 属性 绑定意味着 angular 理解从数据源到视图目标是单向的。

更多请访问www.codementor.io

一般来说,我们可以说只有当我们有一个固定的字符串时才应该使用不带括号的绑定属性:

来自docs

You should omit the brackets when all of the following are true:

  1. The target property accepts a string value.
  2. The string is a fixed value that you can bake into the template.
  3. This initial value never changes.

You routinely initialize attributes this way in standard HTML, and it works just as well for directive and component property initialization.

When setting an element property to a non-string data value, you must use property binding.

总而言之,这意味着右边的值只有在使用括号时才会被解释。只要在右边看到引号中的引号就可以去掉括号:[anyStringProperty]="'hello'"可以改成anyStringProperty = "hello".

因此,属性只要我们在向下传递字符串时也省略双引号之间的单引号,就可以不使用方括号进行绑定。

以下是所有情况的简要说明:

当你使用方括号时,右边是一个表达式。当你根本不使用括号时,右边是一个常量。

因此会将 'constant' 字符串分配给 my-tag 的输入。要用方括号达到同样的效果:注意里面的单引号。如果您没有在此处放置单引号,my-tag 的输入将绑定到其父组件(您编写此模板的位置)属性 或模板变量(例如 ngFor 的 let-constant ) 名为 "constant".

在此处填写What is the difference between property binding and just a regular attribute

来自文档 - Remember the brackets:

The brackets, [], tell Angular to evaluate the template expression. If you omit the brackets, Angular treats the string as a constant and initializes the target property with that string.

有一个小的,也许不重要的情况,但在某些情况下,您错过它可能会很烦人。

数量


案例一

<my-comp [foo]="90"></my-comp>

案例二

<my-comp foo="90"></my-comp>

案例一: typeof foo => 'number'

案例二: typeof foo => 'string'

布尔值


案例三

<my-comp [foo]="true"></my-comp>

案例4

<my-comp foo="true"></my-comp>

案例三: typeof foo => 'boolean'

案例4: typeof foo => 'string'