Trying to change the mat options checkbox value by json data to but not able to change.I have three buttons, Each button have josn data file.If i click the New Data 1 button i want to set the that value for selectOptions, Same for others. How to do it and How to resolve this issue.
app.component.ts:
addData(url) {
this.httpClient.get<any>(url).subscribe((data) => {
this.selectOptions = data;
});
}
Demo : https://stackblitz.com/edit/angular-ivy-kunrso?file=src/app/app.component.html
CodePudding user response:
Instead of ngOnInit(), you should use ngOnChanges that will capture the latest value of selectedOptions to mauto.component.ts.
Inside the ngOnChanges(), you need to patch the value of selectControl, so that filteredData is updated correctly, since your dropdown render's the checkbox options from filteredData, not from rawData. Also, need to reset selectData to remove all the chips.
ngOnChanges(changes: SimpleChanges): void {
if (changes.data && changes.data.currentValue) {
this.rawData = [];
console.log(changes.data.currentValue)
this.data.forEach((item: string) => {
this.rawData.push({ item, selected: false });
});
this.selectData = [];
this.selectControl.setValue(this.rawData)
console.log(this.selectControl)
}
}
CodePudding user response:
Ok, so from the top to bottom:
- In your links in the template you had "grpX.josn" - a simple typo, but it would impossible to fetch data even if it was hosted properly.
- The "assets" should be placed directly under the "app" directory, not in the "app" subdirectory. Hence, they will not be reachable by a http call. Alternatively, you can add your path to the "assets" array in the
angular.json - Once you sort out the above two, you should get a proper response from your http get calls. But note that your
MautoComponentdoes not listen to changes in your input - you use it once duringngOnInitand then it's not re-used later on. Either re-work your component to rely on the@Input() datato display the items, or implementOnChangeinterface and handle the your logic there.
