Data and event binding with angular.

Continuing with some more angular.

We can bind attributes to view elements in angular. We also can register events. Lets check out our app.component.ts class.

export class AppComponent {
  title = 'Hello World';
  image: string = "https://picsum.photos/200/300";
  sayHello() : void {
     console.log( this.image + " - event")
  }
}

Whats new. We added a new class attribute called image. Here we add an URL to a picture. Notice how this attribute was declared.

 image: string = "https://picsum.photos/200/300"

After the image attribute we have a colon and string. In TypeScript we can add types to our attributes.

Next we have a function. We give it a type void because it doesn’t return anything.

  sayHello() : void {
     console.log( this.image + " - event")
  }

It echoes to the console the image URL that we added a string to. We can access the image attribute within our class by using keyword this.

Great lets now go to our view component. The app.component.html file.

Our main changes are shown below.

<img [src]="image" width="200px"><br>
<button (click)="sayHello()">Click me</button>

We can bind an attribute using square brackets [ ]. The src attribute is common to the img element tag. We bind the attribute to our image property in the component class.

The event bind occurs the same way we just use normal brackets ( ). We add a click attribute to our button with brackets and set it equal to our sayHello function in the component class. Once the button is pressed we can see the output.

Now we know how to get feedback from the user using event binding. We can also further dynamically modify our views with data binding.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s