Reputation: 467
Trying to check the mat checkbox by passing the values, But it is not working. If i click the button checkbox should be checked by passing the values. So, How to do it? If anyone knows please help to find the solution.
app.component.ts:
checkValues(val: any) {
let getVal = val.split(',');
getVal.forEach((element: any) => {
this.cardValue.options.push(element);
console.log(element);
});
}
app.component.html:
<mat-card class="card-wrapper">
<app-mauto
#child
placeholder="Select Items Here ..."
key="options"
[data]="selectOptions"
(result)="selectChange($event)"
>
</app-mauto>
</mat-card>
<div class="btnBox">
<button (click)="checkValues('Car,Bus')">Select Checkbox Car and Bus</button>
<button (click)="checkValues('Motor,Bus')">
Select Checkbox Motor and Bus
</button>
<button (click)="checkValues('Wheel,Bus')">
Select Checkbox Wheel and Bus
</button>
</div>
Demo : https://stackblitz.com/edit/angular-ivy-xhg8k2?file=src%2Fapp%2Fshared%2Fmauto%2Fmauto.component.ts
Upvotes: 1
Views: 1866
Reputation: 13307
Your code is using too many variables, and they are not mapped between parent and child component accordingly, thus you are not seeing updated checkboxes on clicking the button.
Here are some of things I did to get it working:
ngOnChanges
to child, so that it can capture the events from parent's buttons and execute the update functionNote: All these changes have removed have the removed filter functionality from the dropdown. I have not addressed since it's not in the scope of this question.
app.component.ts:
selectOptions: Array<string> = [];
...
...
checkValues(val: any) {
this.selectOptions = [];
let getVal = val.split(',');
getVal.forEach((element: any) => {
this.cardValue.options.push(element);
this.selectOptions.push(element);
console.log(element);
});
}
mauto.component.ts:
allOptions: Array<string> = ['Bus', 'Car', 'Motor', 'Wheel'];
...
...
ngOnInit(): void {
console.log(this.rawData)
let el: HTMLElement = this.myDiv.nativeElement;
el.click();
}
ngOnChanges(changes: SimpleChanges) {
if (changes.data && changes.data.currentValue) {
this.data = changes.data.currentValue;
this.updateSelection();
}
}
...
...
updateSelection = () => {
this.selectData = [];
this.rawData = [];
this.allOptions.forEach((item: string) => {
const index = this.data.indexOf(item);
this.rawData.push({ item, selected: index > -1 });
if (index > -1) {
this.toggleSelection({item, selected: false })
}
});
console.log(this.rawData)
}
mauto.component.html:
<mat-option *ngFor="let data of rawData"
Upvotes: 1