Angular 2 : HTML 属性 绑定

Angular 2 : HTML property binding

我正在尝试了解 HTML 绑定,因为我是 angular 的新手。 有人可以解释以下语法之间的区别吗:

<!-- 1 -->
<button name1 = "name2" >test</button>
<!-- 2 -->
<button (name1) = "name2" >test</button>
<!-- 3 -->
<button [name1] = "name2" >test</button>
<!-- 4 -->
<button ([name1]) = "name2" >test</button>

我在多个地方看到过上面的内容,但无法理解每个案例的用途。

感谢您的帮助!

有两种不同的想法..绑定和事件:

这是一个现场演示:https://plnkr.co/edit/gfJL9RCyYriqzP9zWFSk?p=preview

绑定

  • 仅绑定固定字符串
<input value="test" />
  • 用表达式语法单向绑定固定字符串
<input [value]="'test'" />
  • 用表达式语法
  • 单向绑定一个变量test
<input [value]="test" />
  • 单向绑定一个变量test
<input value="{{ test }}" />
  • 将变量 test 双向绑定到此输入
<input [(ngModel)]="test" />

事件

  • 将点击事件绑定到我们的 onClick-函数
<button (click)="onClick($event)"></button>

官方文档:https://angular.io/docs/ts/latest/guide/template-syntax.html

这里是事件绑定、字符串插值和属性绑定的实际例子

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  firstString: string = ' This is using string interpolation coming from a variable in a component ';
  secondString: string = 'This is using string interpolation coming from a method in a component ';
  thirdString: string = 'This is using property-binding';
  forthString: string= 'This is the string before you click';



  returnsecondString () {
    return this.secondString;

  }
  onClick(){
 this.forthString= 'This is the string after you click'
  }

}
<div class="col-lg-1">
  <UL class="list-group-item-info">
    <!--Format for string interpolation: {{ a string from type script or any string }} -->
    <!--Format for property binding:    []= ""  -->
    <!--format for event binding:       ()=""   -->
    <li><p> This is an example of string interpolation : {{firstString}}</p></li>
    <li><p> This is an example of string interpolation : {{returnsecondString()}}</p></li>
    <li><p [innerHTML]="thirdString"></p></li>

  <button class="btn btn-primary" (click)="onClick()"> Click here for Event Binding</button> <hr>
  <li><p>{{forthString}}</p></li>

  </UL>
</div>