Angular 2:HTML属性绑定

时间:2017-04-24 06:33:30

标签: html angular binding angular2-directives

我正在尝试理解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>

我已经在多个地方见过,但无法理解每个案例的目的。

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

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

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

<强>装订

  • 只绑定固定字符串
<input value="test" />
  • 使用expression-syntax
  • 单向绑定固定字符串
<input [value]="'test'" />
  • 使用expression-syntax
  • 单向绑定变量test
<input [value]="test" />
  • 单向绑定变量test
<input value="{{ test }}" />
  • 将变量test双向绑定到此输入
<input [(ngModel)]="test" />

<强>事件

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

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

答案 1 :(得分:0)

这是事件绑定,字符串插值和属性绑定的实际示例

&#13;
&#13;
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'
  }

}
&#13;
<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>
&#13;
&#13;
&#13;