简体   繁体   中英

How to add json data to mat options values in angular 14

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%2Fapp%2Fapp.component.html

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)
    }
 
  }

Demo

Ok, so from the top to bottom:

  1. 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.
  2. 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
  3. Once you sort out the above two, you should get a proper response from your http get calls. But note that your MautoComponent does not listen to changes in your input - you use it once during ngOnInit and then it's not re-used later on. Either re-work your component to rely on the @Input() data to display the items, or implement OnChange interface and handle the your logic there.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM