2017-04-24 133 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>