angular tutorials

How to declare model class and use in Angular component : Typescript ?

This tutorial guides on how to declare model class and use in angular component. Let’s see how to create, declare and use the model in our angular component with example.

Declare model class and use in Angular component

In our previous tutorial you had learnt how to generate model in Angular 9 with anguar-CLI automatically.

Just follow the above link if you wanted to know how to generate model class in specific folder. As explained in the above link, Angular model is a class. Therefore to generate angular model through angular-CLI, you need to use class schematic with the option –type=model . And there is no special schematic or sub commands available in the name of model.

The following command will create recipe model typescript file and it’s spec.ts files automatically under recipes folder as shown below.

> ng generate class recipes/recipe --type=model

CREATE src/app/recipes/recipe.model.spec.ts (152 bytes)
CREATE src/app/recipes/recipe.model.ts (22 bytes)

Once you had created angular model, now its time to declare or define how a single recipe should look like. Therefore you can use that Angular model as a blueprint to create objects.

Angular model class declaration

Note, it’s good practice to segregate the model logic in a separate class. Instances or objects of angular models are the one which holds the data. The following “recipe.model.ts” shows how an Angular model declaration will look like.

//Define how single recipe should look like - Blueprint for object
export class Recipe {

    public name : string;
    public description : string;
    public imagePath : string;

    constructor(name : string, desc : string, imagePath : string){
        this.name = name;
        this.description = desc;
        this.imagePath = imagePath;
    } 

}

Also, there is one more way that you can declare your angular model. Typescript offers another shortcut method to get rid of the property declarations and the content or the body of constructor method declarations.

You can simply add the public accessors in front of the arguments defined in the constructor as shown below.

export class Recipe {

    constructor(public name : string, public desc : string, public imagePath : string){  }
}

When you use the above shortcut method Angular takes care of automatically creating the property declarations and the assignment statements in the constructor body behind the scene.

Therefore, the second method looks like nice and convenient short cut method to declare model class in Angular.

Use Model in Angular Component

In the previous steps, you had created the model and declared successfully. Now let’s see how to use that model in your Angular component.

In our another tutorial we have seen how to use recipe model in recipe-list component of myrecipes.com website. The following are the code sneppets on how to use the model in an angular component.

recipe-list.component.ts

Note, you need to import recipe model in your angular component class using import statement and declare recipe array in RecipeListComponent class and create recipe objects with new operator as shown below.

import { Component, OnInit } from '@angular/core';
import { Recipe } from '../recipe.model';

@Component({
  selector: 'app-recipe-list',
  templateUrl: './recipe-list.component.html',
  styleUrls: ['./recipe-list.component.css']
})
export class RecipeListComponent implements OnInit {

  recipes: Recipe[] = [
    new Recipe('Recipe 1', 'This is our first recipe', 'https://lillunacom/wp-content/uploads/2017/10/spanish-rice-resize-6.jpg'),
    new Recipe('Recipe 2', 'This is our second recipe', 'https://foodfnrsndimgcom/content/dam/images/food/fullset/2020/07/14/0/FNK_20-Minute-Sausage-And-Pepper-Ravioli-Skillet_H_s4x3.jpg.rend.hgtvcom.441.331.suffix/1594757098344.jpeg'),
    new Recipe('Recipe 3', 'This is our third recipe', 'https://imagessquarespace-cdncom/content/v1/5c089f01f93fd410a92e642a/1589512502567-CNOAIL05BVT1TI0422P2/ke17ZwdGBToddI8pDm48kLkXF2pIyv_F2eUT9F60jBl7gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z4YTzHvnKhyp6Da-NYroOW3ZGjoBKy3azqku80C789l0iyqMbMesKd95J-X4EagrgU9L3Sa3U8cogeb0tjXbfawd0urKshkc5MgdBeJmALQKw/pheasant+back+burger+recipe.jpeg'),
    new Recipe('Recipe 4', 'This is our fourth recipe', 'https://encrypted-tbn0gstaticcom/images?q=tbn%3AANd9GcQunf0MIpWZn3rjR-mo4u9_HKsL0Ud3SV8WTQ&usqp=CAU'),
    new Recipe('Recipe 5', 'This is our fifth recipe', 'https://encrypted-tbn0gstaticcom/images?q=tbn%3AANd9GcQ_9l39e7G5y_ENz6hL6l5KhaJuroOrbzqs0Q&usqp=CAU')
  ];

  constructor() { }

  ngOnInit(): void {
  }

}

recipe-list.component.html

<div class="row">
    <div class="col-xs-12">
        <div class="pull-left">
            <h3>My Recipe List</h3>
        </div>   
    </div>
</div>
<hr>
<div class="row">
    <div class="col-xs-12">
        <a href="#" 
           class="list-group-item clearfix" 
           *ngFor="let recipe of recipes">
            <div class="pull-left">
                <h4 class="list-group-item-heading">{{ recipe.name }}</h4>
                <p class="list-group-item-text">{{ recipe.description }}</p>
            </div>
            <span class="pull-right">
                <img 
                     [src] = "recipe.imagePath"
                     alt="{{ recipe.name }}" 
                     class="img-responsive" 
                     style="max-height: 50px;"> 
            </span>
        </a>        
    </div>
</div>
<hr>
<div class="row">
    <div class="col-xs-12">
        <div class="pull-right">
            <button class="btn btn-success">Add Recipe</button>
        </div>        
    </div>
</div>



That’s it. You had learnt how to declare model class and use in angular component.

Hope it helped 🙂

Also See:

References:

 

guest
0 Comments
Inline Feedbacks
View all comments