Can you explain how I can showcase JSON object values within an Angular framework?

After fetching data through a REST API in Angular, I need to display only the "classLevelPermissions" in table format as shown in the .html file.

.ts -

async getclp(className: string) {
    debugger;
   this.clplist = [];  
   this.className = className; 
    var kk1 = [];
    this.clpcollist = [];
    await this.rec.getclpdata(this.className).toPromise().then(result => {
      this.clplist.push(result);

    }, (error) => {
      alert("Failed" + error.message);
    });
  }

service.ts -

 getclpdata(className :string)
  {

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'X-Parse-Application-Id': configuration.PARSE_KEY,
        'X-Parse-Master-Key': configuration.PARSE_MASTER_KEY,
      })

    };
        return this.http.get<any>(this.geturl + className,httpOptions).pipe(
        map(result => {
          console.log(result);
          return result;
        })
      );
  }

.html -

<div class="modal-body modal-lg">
    <div class="row">
      <div class="col-md-12">
        <div class="table-responsive">
          <table class="table table-striped table-bordered table-hover table-checkable order-column valign-middle"
            id="example4">
            <thead>
              <tr>
                <th>Sr.No</th>
                <th>Role Name</th>
                <th>Find</th>
                <th>Get</th>  
                <th>Create</th>
                <th>Update</th>
                <th>Delete</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>

              <tr *ngFor=" let res of clplist ; let i = index;">
                <td>{{i + 1}}</td>
                <td>{{res.result.classLevelPermissions.find}}</td>
                <td>{{res.result.classLevelPermissions.get}}</td>
                <td>{{res.result.classLevelPermissions.create }}</td>
                <td>{{res.result.classLevelPermissions.update }}</td>
                <td>{{res.result.classLevelPermissions.delete}}</td>
                <td class="center">
             <button class="btn btn-danger btn-sm" (click)="deleteDBField(rlist.fieldName)">
              <i class="fa fa-trash"></i></button>
               </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

I want the output to be formatted exactly like this:

   RoleName     |      Get    |     Find     | Create | Update | Delete
 _superadmin    | public, yes | public, yes  | yes    |  no    | yes

Note: Display "yes" when value is "true", "no" when value is "false". Also, print "Public" when ['*' : true] exists.

Answer ā„–1

give this a shot(.ts code)

 await this.rec.getclpdata(this.className).toPromise().then(result => {
      var obj = {};
      var keyType = Object.keys(result.classLevelPermissions.delete)[0]; 
       obj['roleName'] = keyType.split(':',2)[1]; 
obj['find']= result.classLevelPermissions.find[keyType ]? "Yes" : "No";
obj['isFindPublic']= result.classLevelPermissions.find['*']? "public" : false;
obj['get']= result.classLevelPermissions.get[keyType ]? "Yes" : "No";
obj['isGetPublic']= result.classLevelPermissions.get['*']? "public" : false;
obj['create'] = result.classLevelPermissions.create[keyType ]? "Yes" : "No";
obj['update']= result.classLevelPermissions.update[keyType ]? "Yes" : "No";
obj['delete']= result.classLevelPermissions.delete[keyType ]? "Yes" : "No"; 
this.clplist.push(obj);

give this a shot(.html)

<tr *ngFor=" let res of clplist">
                <td>{{$index + 1}}</td>
                <td>{{res.roleName}}</td>
                <td><span *ngIf="res.isFindPublic">{{res.isFindPublic}}{{","}}</span>{{res.find}}</td>
                <td><span *ngIf="res.isGetPublic">{{res.isGetPublic}}{{","}}</span>{{res.get}}</td>
                <td>{{res.create }}</td>
                <td>{{res.update }}</td>
                <td>{{res.delete}}</td>
                <td class="center">
             <button class="btn btn-danger btn-sm" (click)="deleteDBField(rlist.fieldName)">
              <i class="fa fa-trash"></i></button>
               </td>
              </tr>

Answer ā„–2

If you want to convert true or false values to Yes or No, you can use a pipe. A complete working example can be found at this StackBlitz Link

This is how your HTML template should look like...

<table>
      <th *ngFor = "let row of data">
         {{getkeys(row)}}
      </th>
      <tr>
           <td *ngFor="let row of data index as i">{{ i === 0 ? row.roleName :  row[getkeys(row)].role | yesno }}</td>
      </tr>
</table>

The custom yesno pipe implementation would be like this...

transform(value: any, args?: any): any {
  return value ? 'Yes' : 'No';
}

In the component, your sample JSON Object data could look something like this...

ngOnInit(){
this.data = [{roleName:"_superadmin"}, {
  create : {role: "true"}
},
{
  findd : {role: "true"}
},
{
  deletee : {role: true}
},
{
  gett : {role: true}
},
{
  update : {role: false}
}];

}
getkeys(data){
 return Object.keys(data);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the correct method for typing a React functional component with properties?

Here's a react functional component I have created... const MyFunction = () => { // lots of logic MyFunction.loaded = someBoolean; return <div>just one line</div> } MyFunction.refresh = () => ....... I added two properti ...

How can I create a universal "Add" button in Angular that can be used across all child components?

Currently, I am working on a straightforward application featuring a toolbar at the top of the screen. Within this toolbar, there is a + button designated for adding content. The functionality of this + button changes based on which component is currently ...

Error occurs when attempting to filter data through input text pasting in Angular

Currently, I am working on a web application that utilizes the Angular framework and angularfire2. The issue I am encountering is related to the data filter functionality not functioning correctly when pasting copied text. Interestingly, it works perfectly ...

Restrict the properties of an object to match the properties of a different object

I am currently developing an Object patching utility function with the following code snippet class Test{ a:number; b:number; } var c:Test={a:0,b:1} function patchable<T>(obj:T){ return { patch:function<K>(prop:K){ return patc ...

Configuring SSL for an AWS Mean Stack deployed on an EC2 instance with ngInx hosting

Currently in the process of setting up SSL/https for my website, following steps from various sources but encountering some issues. Seeking guidance. Here are the steps I have taken so far: Hosted my MEAN stack website on EC2 in AWS. Both UI and Bac ...

Once data is assigned to a variable within a subscribe method, it will no longer be available after the method has been completed

I'm currently working with the signature_pad library, and I have encountered an issue. When I draw a line, the method toDataURL() returns a string. I have a MessagingService set up to send this string between different Angular components. The goal is ...

Tips for manually inputting dates in Primeng Calendar Datepicker with the slash "/" symbol

I need assistance with adding slashes to manual input when using the primeng Calendar component. <p-calendar [monthNavigator]="true" [yearNavigator]="true" yearRange="1950:2021" ngModel [required]="tru ...

Changing email case with Angular reactive forms upon submission

I have a reactive form that allows users to enter email addresses with uppercase characters before the '@' symbol. However, I need to convert a valid email address like '[email protected]' to '[email protected]' onSu ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

Evaluation of button display based on certain conditions

I currently have two different render functions that display certain elements based on specific conditions. The first render function looks like this: private render(): JSX.Element { return ( <div> {this.props.x && this.state.y ...

Tips on how to flatten an Array of Observables within an Observable

I've been attempting to flatten a nested Observable, but I'm struggling to make it work as intended: this.af.object('test/father') .map(res => { res.namedKeys = []; for (let el in res.keys) { res.namedKeys.push(this ...

Tips for positioning an inline label and input field in an Angular application using CSS and HTML: How to align the label to the left and the input

I'm currently developing an Angular form with multiple label-input field combinations. I have managed to style the labels and input fields with inline block so that they appear on the same row. However, I am facing a challenge in aligning the label to ...

Issue with ambient contexts error in TypeScript constructor

What is the correct way to create a constructor in TypeScript? I have been researching and trying different approaches, but it seems like the syntax has changed. Here is my latest attempt: car.d.ts declare class Car { constructor(public engine: string ...

The matInput value remains stagnant and fails to update

I am encountering an issue with a form Input field for username and password. Here is the code snippet: <mat-form-field class="mdb-form-field-modal form-adjustments"> <input (keydown)="emailBtnFocus($event)" tabindex="0" matInput placeholder ...

Storing data retrieved from a GraphQL response into the sessionStorage: A step-by-step guide

I am facing a challenge in saving my GraphQL response in sessionStorage to access it across different parts of the application without making repeated API calls. I am currently using the useQuery hook with a skip property to check if the data is already st ...

Creating a generic component map resolver for flexible applications

Currently, I am engaged in a project where the backend allows for the modeling of dynamic content that is later displayed as Components on the frontend. Everything seems to be functioning well, except when dealing with models where the dynamic content con ...

The upcoming development does not involve creating an entire HTML webpage using on-demand static site generation (SS

Iā€™m encountering a problem when utilizing getStaticPaths and getStaticProps to create an on-demand SSG for a sharing page. My setup involves Next v12.1.0 and React 17.0.2. After building a specific /[id] page, I can retrieve the data but the HTML output ...

What steps can I take to stop Vetur and TypeScript from displaying duplicate TypeScript warnings in VSCode?

I have a Vue2 project using TypeScript in VSCode with Vetur and TypeScript extensions installed. Whenever there is a TypeScript warning, both the TypeScript and Vetur overlays show duplicate warnings. Example of duplicate warnings Also, the intellisense ...

Issue with bi-directional data binding in Angular's matInput component

When working on my template... <input matInput placeholder="Amount" [(value)]="amount"> In the corresponding component... class ExampleComponent implements OnInit { amount: number = 0; ... } The binding doesn't seem to work as expect ...

React's componentDidUpdate being triggered before prop change occurs

I am working with the CryptoHistoricGraph component in my app.js file. I have passed this.state.coinPrices as a prop for this element. import React from 'react'; import axios from 'axios'; import CryptoSelect from './components/cry ...