Dynamically Set or Assign Label Text on Button Click in Angular 4

This may not be a very common scenario, however sometimes you might need it, that is, assigning or setting the label text dynamically. Here, I am sharing two different methods showing how to set or assign the text of a label dynamically on button click in your Angular 4 application.

The label (in both the methods) will get its value from an input box (input type text). Therefore, I have a textbox (for the value), a button (will call a function) and the label (with no text) in my app’s template.

1st Method (Passing values to function)

You can “pass multiple parameters to a function” from your Angular 4 template. Therefore, in my first method, I have a function in my component class, which will receive the values as parameters, using which I’ll set or assign text to the label, dynamically.

The button’s click event will call the function named changeLabelName().

Here’s how you should do it.

The Template
Enter a value <input type="text" #tbName id="tbName">
<p>
    <button type="submit" (click)="changeLabelName(lblName.id, tbName.value)" id="bt">
        Click Me
    </button>
</p>

<ng-container>
    <p>
        <label #lblName id="lblName">

        </label>
    </p>
</ng-container>

Look at the syntax in the input box and the Label. I have used the # or the hash symbol with the elements. That’s how you should declare template reference variables (or simply variables) in Angular.

Defining a variable using the # symbol allows you to access the DOM element. I am using the variables to pass the input value and the label’s id, to a function in my component class.

The Application Component
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  ngOnInit () {  }

  changeLabelName(lbl, val) {
    document.getElementById(lbl).innerHTML = val;
  }  
}

Ok, I am using the innerHTML property to assign a new text to the label. This is very common. I am sure you might have used this property in your JavaScript application. Yes, you can also use the innerText property.

With innerHTML, you can add any HTML codes with the text. For example, if you want to keep on adding values to the label, you can do something like this …

document.getElementById(lbl).innerHTML += '<br />' + val;

With innerText, add only text values like numbers, string etc. If you add HTML code here, the property will show the HTML as it is along the text.

2nd Method (Using Custom two-way binding)

In the 2nd method I am using the two-way binding method to assign text to the label. Since, I want to assign text to the label on button click, I’ll call a function on button click. However, I am not passing any parameters to the function, like shown in the 1st method (or example) above.

The Template
Enter a value <input type="text" [(ngModel)]="str">
<p>
    <button type="submit" (click)="changeLabelName()" id="bt">
        Click Me
    </button>
</p>

<ng-container>
    <p>
        <label id="lblName">
            {{name}}
        </label>
    </p>
</ng-container>

Usually, with the two-way data binding method using [(ngModel)], you could have easily assigned the input value to the label, like this…

Enter a value <input type="text" [(ngModel)]="name">
<label id="lblName"> {{name}} </label>

When you type in the input box (the model), the value is simultaneously written into the view. However, I am not binding the view with the model (see the template above). I have to assign value only after clicking the button. I’ll do it through the function in my component class.

Update Module.ts

First, update your module class. If you are using [(ngModel)], you’ll have to first import the FormsModule class in your app.module.ts file.

Please read this post, to avoid Can’t Bind to ngModel since it isn’t a known property error.

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
The Application Component
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  ngOnInit () {  }
  
  public name:any;
  public str:any;

  changeLabelName() {
    this.name = this.str;
  }  
}

I have two public variables, name and str. The variable str gets it value from input box and then assigns the value to the name variable, bound to an expression {{ name }} in our application template.

That’s it.

Previous - How to Highlight Table Row in ngFor on Hover in Angular 4Next - AutoComplete Textbox in Angular 6 with Dynamic Data using Web API in MVC 4



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!