Open In App

Ember.js Ember.Templates.helpers component() Method

Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of websites, including Square, Discourse, Groupon, Linked In, Live Nation, Twitch, and Chipotle.

The component() method is used to lets you to add the instance of the component to templates.



Syntax:

{{ component functionName }} 

Parameters:



Return Value: It doesn’t return anything.

Steps to Install and Run Ember.js:

Step 1: To run the following examples you will need to have an ember project with you. To create one, you will need to install ember-cli first. Write the below code in the terminal:

npm install ember-cli

Step 2: Now you can create the project by typing in the following piece of code:

ember new <project-name> --lang en

To start the server, type:

ember server

Example 1: Type the following code to generate the route for this example:

ember generate route component1

app/controllers/component1.js




import Ember from 'ember';
import { tracked } from '@glimmer/tracking';
 
export default Ember.Controller.extend({
    @tracked isComp: 'true',
    get isComponent(){   
    return this.isComp ? 'compact' : 'compact2';
},
    get isComponent2(){
        return this.isComp ? 'compact2' : 'compact';
    },
});

app/component/compact.hbs




<h1>this is first Component !!!</h1>

app/component/compact2.hbs




<h1>this is Second component!!</h1>

app/template/component.hbs




{{component this.isComponent}}
<br/><br/>
{{component this.isComponent2}}

Output:

Ember.js Ember.Templates.helpers component() Method

Example 2: Type the following code to generate the route for this example:

ember generate route component2

app/controllers/component2.js




import Ember from 'ember';
import { tracked} from '@glimmer/tracking';
import { action} from '@ember/object';
 
export default Ember.Controller.extend({
    @tracked isComp: false,
    get isComponent(){
        return this.isComp ? 'compact' : 'compact2';
      },
    @action
      flip(){
        this.isComp = ~this.isComp;
      }
});

app/component/compact.hbs




<h1>this is first Component !!!</h1>

app/component/compact2.hbs




<h1>this is Second component!!</h1>

app/templates/component2.hbs




{{component this.isComponent}}
 
<input type="button" id="decrease"
    value="Change" {{action 'flip'}}/>

Output:

Ember.js Ember.Templates.helpers component() Method

Reference: https://api.emberjs.com/ember/4.4/classes/Ember.Templates.helpers/methods/component?anchor=component


Article Tags :