Angular (version 7)
If items are prepared in json format as follows, I would like to substitute foo with a specific message and pass it to html to display the value by conditional branching of the hoge() function.
hoge
in component.tsitems:{
"price"—200,
"count"—5
},
{
"price"—50,
"count"—3
},
{
"price"—0,
"count"—3
},
component.ts
// json data for items
public items —Items;
// Displayed on screen
public foo:string;
ngOnInit{
This.hoge();
}
public hoge(){
// retrieve json's items data one by one
This.items.forEach(item=>{
// If the price of the extracted data is 100 or more, replace the value to be displayed on the screen.
if(item.price>=100){
This.foo = 'Hugging' 1;
// If the price is greater than 1 and less than 100 in the extracted data, replace the value with the value displayed on the screen.
} else if (item.price>1&100>=item.price) {
This.foo = 'Hugging 2';
// If not above, replace the value to be displayed on the screen.
} else{
This.foo = 'It's empty';
}
});
}
html
<div*ngFor="let items of items">
<div>{{hoge}}</div>
</div>
The expected behavior is
Whistle 1
Huge 2
Empty
The content is
·If the price is 100 or more, the price is '1
·If the price is 1<=100, I'd like to buy Hogue 2
·Other than that, it's empty
should be displayed as
However, at the moment, it is only displayed as empty.
Perhaps the reason is that there are three items data, but I was wondering if it was called by replacing the empty with else and price 0 pattern with foo, but I couldn't think of a specific solution to display each message.
There are two solutions,
For 1, change public hoge
to the following code
public hoge(){
This.items.forEach(item,idx)=>{
if(item.price>=100){
This.items [idx]['foo'] = 'Hog Hog 1';
} else if (item.price>1&100>=item.price) {
This.items [idx]['foo'] = 'Hugging 2';
} else{
this.items [idx]['foo'] = 'empty';
}
});
}
For 2, change the html
to the code below
<div*ngFor="let items of items">
<div*ngIf="item.price>=100"> Hog Hog 1</div>
<div*ngIf="item.price>1&100>=item.price">Hoege 2</div>
<div*ngIf="item.price==0">empty</div>
</div>
The sample code is Here
© 2024 OneMinuteCode. All rights reserved.