Reputation: 169
In my angular app i have two arrays arr1, arr2, where i am using arr1 to render button in my view using ngFor. I want to change the style of button by comparing the items of arr1 and arr2. if there is a match, i want to apply different styling. How can i implement this please guide me.
app.component.ts
arr1 = [{test:1}, {test:2}, {test:3}, {test:4}, {test:5}, {test:6}, {test:7}, {test:8}, {test:9}, {test:10}]
arr2 = [{test:5}, {test:9}]
appCopmponent.html
<div class="col-md-12">
<div class="form-row">
<div class="col-md-1" *ngFor="let data of arr1">
<input type="button" class="form-control" [(ngModel)]="data.test" readonly>
</div>
</div>
</div>
Upvotes: 1
Views: 1481
Reputation: 1245
Compare your array into the component file.
compareValue(data){
if(this.arr2.find(o => o.test === data.test)){
return true;
}else{
return false;
}
}
Call the function from html and add your style class using ngClass
.
<div class="col-md-12">
<div class="form-row">
<div class="col-md-1" *ngFor="let data of arr1">
<input type="button" class="form-control" [ngClass]="{'success':compareValue(data)}" [(ngModel)]="data.test" readonly>
</div>
</div>
Upvotes: 1
Reputation: 1085
You can with using ngClass
attribute.
.ts file
arr1 = [{test:1}, {test:2}, {test:3}, {test:4}, {test:5}, {test:6}, {test:7}, {test:8}, {test:9}, {test:10}]
arr2 = [{test:2}, {test:1}];
contains: boolean;
ngOnInit() {
this.contains = !this.arr2.filter(item => !this.arr1.find(x => x.test === item.test)).length;
}
on template
<p [ngClass]="contains? 'bg-blue': 'bg-red'">
Change background based on array comparison
</p>
css file
.bg-red {
background-color: red
}
.bg-blue {
background-color: blue
}
Also I created a StackBlitz example for you.
Upvotes: 1
Reputation: 636
you can use [ngClass]
for assigning style class based on your need
https://stackblitz.com/edit/angular-material-starter-l1c9t5?file=app%2Fapp.component.ts
<div class="col-md-12">
<div class="form-row">
<div class="col-md-1" *ngFor="let data of arr1">
<input [ngClass]="founded(data) ? 'exist' : 'not-exist'" type="button" class="form-control" [(ngModel)]="data.test" readonly>
</div>
</div>
</div>
<style>
input{
padding: 0 2rem;
margin: 1rem 0
}
.exist{
border: orange solid 5px;
}
.not-exist{
border: green solid 5px;
}
</style>
and code:
arr1 = [{test:1}, {test:2}, {test:3}, {test:4}, {test:5}, {test:6}, {test:7}, {test:8}, {test:9}, {test:10}]
arr2 = [{test:5}, {test:9}]
founded(item: {test: number}){
return !!this.arr2.find(x=>x.test === item.test)
}
Upvotes: 1