Monday, February 13, 2017

Aurelia - Components

Components are main building blocks of Aurelia framework. This chapter will show you how to create simple components.

Simple Component

You already saw components in previous chapters. Each component contains view-model which is written in JavaScript and view, written in HTML. You can see our view-model definition below. This is an ES6 example but you can also use TypeScript.

app.js

export class MyComponent {
   header = "This is Header";
   content = "This is content";
}
We can bind our values to the view as shown in example below. ${header} syntax will bind the defined header value from MyComponent. The same concept is applied for content.

app.html

<template>
   <h1>${header}</h1>
   <p>${content}</p>
</template>
The above code will produce following output −
Aurelia Components Simple

Component Functions

If you want to update header and footer when user clicks the button, you can use the following example. This time we are defining header and footer inside EC6 class constructor.

app.js

export class App{  
   constructor(){
      this.header = 'This is Header';
      this.content = 'This is content';
   }

   updateContent(){
      this.header = 'This is NEW header...'
      this.content = 'This is NEW content...';
   }
}
We can add click.delegate() to connect updateContent() function with the button. More on this in one of our next chapters.

app.html

<template>
   <h1>${header}</h1>
   <p>${content}</p>
   <button click.delegate = "updateContent()">Update Content</button>
</template>
When button is clicked, header and content will be updated.
Aurelia Components Method

No comments:

Post a Comment