English 中文(简体)
Angular 2 - User Input
  • 时间:2024-09-17

Angular 2 - User Input


Previous Page Next Page  

In Angular 2, you can make the use of DOM element structure of HTML to change the values of the elements at run time. Let’s look at some in detail.

The Input Tag

In the app.component.ts file place the following code.

import { 
   Component 
} from  @angular/core ;  

@Component ({ 
   selector:  my-app , 
   template:   
      <span> 
         <input [value] = "name" (input) = "name = $event.target.value"> 
         {{name}} 
      </span> 
     
}) 
export class AppComponent { }

Following things need to be noted about the above code.

    [value] = ”username” − This is used to bind the expression username to the input element’s value property.

    (input) = ”expression” − This a declarative way of binding an expression to the input element’s input event.

    username = $event.target.value − The expression that gets executed when the input event is fired.

    $event − Is an expression exposed in event bindings by Angular, which has the value of the event’s payload.

Once you save all the code changes and refresh the browser, you will get the following output.

You can now type anything and the same input will reflect in the text next to the Input control.

Input Tag

Cpck Input

In the app.component.ts file place the following code.

import {
   Component
} from  @angular/core ;

@Component ({
   selector:  my-app ,
   template:  <button (cpck) = "onCpckMe()"> Cpck Me </button> {{cpckMessage}} 
})

export class AppComponent {
   cpckMessage =  Hello ;
   onCpckMe() {
      this.cpckMessage =  This tutorial! ;
   }
}

Once you save all the code changes and refresh the browser, you will get the following output.

Cpck me

When you hit the Cpck Me button, you will get the following output.

Cpck me Button Advertisements