stackflow
stackflow

Reputation: 2122

Angular 2 : HTML property binding

I'm trying to understand the HTML bindings as I'm new to angular. Can someone please explain the difference between the following syntax:

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

I have seen above in multiple places but could not understand the purpose of each case.

Thank you for the help!

Upvotes: 1

Views: 1487

Answers (2)

William Pourmajidi
William Pourmajidi

Reputation: 1036

Here is a practical example of event-binding, string-interpolation, and property binding

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>

Upvotes: 0

slaesh
slaesh

Reputation: 16917

There are two different thinks.. bindings and events:

Here's a live-demo: https://plnkr.co/edit/gfJL9RCyYriqzP9zWFSk?p=preview

Binding

  • binds just a fixed string
<input value="test" />
  • one-way binding a fixed string with expression-syntax
<input [value]="'test'" />
  • one-way binding a variable test with expression-syntax
<input [value]="test" />
  • one-way binding a variable test
<input value="{{ test }}" />
  • two-way bindig the variable test to this input
<input [(ngModel)]="test" />

Events

  • bind click-event to our onClick-function
<button (click)="onClick($event)"></button>

official docs: https://angular.io/docs/ts/latest/guide/template-syntax.html

Upvotes: 4

Related Questions