I have an array of numbers, and I need to display these numbers and their respective squares along with it. For this I need to define a function which take number as an parameter and returns its square as a value.I have tried defining a function as
Numbers:number[]=[2,3,5,7];
square(cm:number):number{
return cm*cm;
}
You need to use {{square(c1)}}
so that you call the method and get the squared value
<h4> List Of Numbers</h4>
<div class="row"*ngFor="let c1 of Numbers;index as i">
<div class="col-1 m-1">
{{i}}
</div>
<div class="col-2 border bg-light m-1">
{{c1}}
</div>
<div class="col-2 border bg-light m-1">
{{square(c1)}}
</div>
<div class="col-1 border fa fa-trash m-1 bg-white" (click)="remove(c1)">
</div>
You can use map function
var number = [2, 3, 5, 7];
var square = number.map(c=> c*c);
You are using it wrong way .Call your function in the html.
<h4> List Of Numbers</h4>
<div class="row" *ngFor="let c1 of Numbers;index as i">
<div class="col-1 m-1">
{{i}}
</div>
<div class="col-2 border bg-light m-1">
{{c1}}
</div>
<div class="col-2 border bg-light m-1">
{{square(c1)}}
</div>
<div class="col-1 border fa fa-trash m-1 bg-white" (click)="remove(c1)">
</div>
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'square',
})
export class SquarePipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
return value * value
}
}
html:
<ng-container *ngFor="let item of iterms">{{ item | square}}</ng-container>
module.ts:
declarations:[SquarePipe ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.