What's the difference between `value=“{{todo.title}}”` and `[value]=“todo.title”`?

前端 未结 2 1013
闹比i
闹比i 2020-12-19 10:51

I have been doing a todo app in Angular 2 to graps the concepts... What\'s the difference between value=\"{{todo.title}}\" and [value]=\"todo.title\"

相关标签:
2条回答
  • 2020-12-19 11:19

    From Angular doc:

    Property binding or interpolation?

    We often have a choice between interpolation and property binding. The following binding pairs do the same thing:

    <p><img src="{{heroImageUrl}}"> is the <i>interpolated</i> image.</p>
    <p><img [src]="heroImageUrl"> is the <i>property bound</i> image.</p>
    
    <p><span>"{{title}}" is the <i>interpolated</i> title.</span></p>
    <p>"<span [innerHTML]="title"></span>" is the <i>property bound</i> title.</p>
    

    Interpolation is a convenient alternative for property binding in many cases. In fact, Angular translates those interpolations into the corresponding property bindings before rendering the view.

    There is no technical reason to prefer one form to the other. We lean toward readability, which tends to favor interpolation. We suggest establishing coding style rules and choosing the form that both conforms to the rules and feels most natural for the task at hand.

    Link

    0 讨论(0)
  • 2020-12-19 11:35

    Let's say we have this data

    todo = {
      title: 5
    };
    

    1) value="todo.title" - the attribute with name value and value "todo.title" (string)

    2) value="{{todo.title}}" - the property with name value and value "5" (always string)

    template_parser.ts method _parseAttr

    Therefore it won't be included as the attribute

    3) [value]="todo.title" - the property with name value and value 5 (number)

    So difference between those expressions is that the value in the interpolation (value="{{todo.title}}") is always stringified while the value of basic property binding ([value]="todo.title") is passed as is.

    0 讨论(0)
提交回复
热议问题