XamarinDevil
XamarinDevil

Reputation: 891

How to bind data to label in angular2

Is it possible to bind data to a label using ngModel? I want to display data fetched from the database and display using labels and not input(textbox).

Upvotes: 9

Views: 49992

Answers (4)

Roman C
Roman C

Reputation: 1

The ngModel only works for form's input controls. The label is not a form control.

You can bind other properties with [] i.e. the property binding.

<label [value]="expression"/>

Upvotes: 0

Hameed Syed
Hameed Syed

Reputation: 4265

One of the way to achieve two way data binding for the label control.

  <label for="name">{{name}}</label>

in your ts

export class MyComponent {
           name="Wick";    
      //one of the hrml controls calls this method
           somebodyCalledMe(){
          this.name="John Wick";
}

So now whenever the name property changes automatically the label's text will also change accordingly.

Upvotes: 2

Yoav Schniederman
Yoav Schniederman

Reputation: 5391

There are 3 options :

  1. <label [value]="someValueExpression"/>
  2. <label>{{ value}}</label>
  3. when you are using form:

    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" required>
    

Upvotes: 15

Suren Srapyan
Suren Srapyan

Reputation: 68655

ngModel works only for form's controls, which get input from the user. You need to use {{ }} syntax.

<label>{{ yourData }}</label>

Upvotes: 5

Related Questions