2017-04-24 128 views
0

我想了解HTML绑定,因为我是新的角。 能有人请解释下面的语法之间的区别:角2:HTML属性绑定

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

我已经在多个地方上面看到的,但无法了解每个案件的目的。

谢谢你的帮助!

+0

https://angular.io /docs/ts/latest/guide/template-syntax.html#!#twoway –

+2

我认为[绑定语法](https://angular.io/docs/ts/latest/guide/template-syntax.html# !#binding-syntax)i就是你正在寻找 –

回答

2

有两种不同的认为..绑定和事件:

这里有一个实时演示:https://plnkr.co/edit/gfJL9RCyYriqzP9zWFSk?p=preview

绑定

  • 结合只是一个固定字符串
<input value="test" /> 
  • 单向结合一个固定的字符串用表达式语法
<input [value]="'test'" /> 
  • 单向结合的可变test与表达语法
<input [value]="test" /> 
  • 单向绑定变量test
<input value="{{ test }}" /> 
  • 双向bindig变量test该输入
<input [(ngModel)]="test" /> 

活动

  • 绑定点击事件给我们的onClick功能全
<button (click)="onClick($event)"></button> 

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

+0

thanksMxii,你能告诉我之间的区别,<输入[值] =“测试” />和<输入值=“{{测试}}” />? –

+0

实际上没有。 :)只是语法。 – mxii

0

这里是事件结合,串插的一个实际的例子,和属性绑定

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>