【问题标题】:Angular 2 : HTML property bindingAngular 2:HTML 属性绑定
【发布时间】:2017-09-20 17:33:28
【问题描述】:

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

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

感谢您的帮助!

【问题讨论】:

标签: html angular binding angular2-directives


【解决方案1】:

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

这是一个现场演示: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-function
<button (click)="onClick($event)"></button>

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

【讨论】:

  • thanksMxii,你能告诉我, 之间的区别吗?
  • 实际上没有。 :) 只是语法。
【解决方案2】:

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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2019-04-08
    • 2018-02-13
    • 2016-07-21
    相关资源
    最近更新 更多