Adding two numbers in Angular with @Input

Problem: You want a tag which takes two parameters and return the sum on the screen. Something like:

<sum first="5" second="4"/>        

Solution:

  1. Open a console (like Terminal in Mac OS X) and go to the folder where your Application is, like app.
  2. Create the sum component with ng generate component sum
  3. Go to your favorite IDE (like WebStorm)
  4. modify the content of sum.component.ts
  5. modify the content of sum.component.html
  6. use the new sum tag in app.component.html

That's it! 😃

sum.component.ts:

import {Component, Input} from '@angular/core';

@Component({
  selector: 'sum',
  standalone: true,
  imports: [],
  templateUrl: './sum.component.html',
  styleUrl: './sum.component.css'
})
export class SumComponent {
  @Input() first = '';
  @Input() second = '';

  sum(): Number {
    return Number.parseInt(this.first) + Number.parseInt(this.second)
  }
}        

sum.component.html:

{{sum()}}        

To view or add a comment, sign in

More articles by Bojan Antonović

Explore content categories