Having trouble implementing conditional rendering for components sourced from a .json/.ts file in Angular

Presented below is the JSON file which includes a .text component with a text field and a .radio component featuring a radio button. How can we efficiently display them conditionally based on the content of the .json file?

Here's the contents of the .json file:

export const questions = 
[
    {
    "question": "What is your name?",
    "type": "text"
    },
    {
    "question": "Are you happy?",
    "type": "radio"  
    },
    {
    "question": "How are you feeling?",
    "type": "text"  
    }
]

Provided below is the .ts file:

import { Component, OnInit } from '@angular/core';
import {questions} from './questions';
import { RadioComponent } from './radio/radio.component';
import { TextComponent } from './text/text.component';

interface q 
{
  question: String;
  type: String;
}

@Component({
  selector: 'app-disposition-wizard',
  templateUrl: './disposition-wizard.component.html',
  styleUrls: ['./disposition-wizard.component.scss']
})




export class DispositionWizardComponent implements OnInit {

  constructor() { }

  ques: q[] = questions;
  
  ngOnInit() {
  }

}

The HTML file displayed below currently showcases both the text and radio components:

<p *ngFor = "let q of ques">{{q.question}}

    
    <app-text></app-text>
   
    <app-radio></app-radio>


</p>

Answer №1

To display different components based on the question type in your ques array, you can utilize *ngFor and *ngIf directives in your Angular template. Refer to ngFor Angular for more information.

After your edit: So if I understand correctly, you wish to show the app-text component when the question type is text and the app-radio component when the question type is radio?

You can achieve this using conditional rendering with *ngIf:

<div *ngIf="q.type === 'radio'"><app-radio></app-radio></div>

<div *ngIf="q.type === 'text'"><app-text></app-text></div>

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 best way to retrieve a member from a union type?

Here is a simple example to illustrate the problem: // library.d.ts import type { Bar } from './bar.d.ts'; export interface Foo { bar?: string | Bar | boolean; // and many other properties } // bar.d.ts export interface Bar { baz?: number ...

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

Informing typescript that an argument is specifically an array when accepting both a single string and an array of strings

How can I inform TypeScript that the code is functionally valid? It keeps suggesting it could be a string, but I am unsure how that would happen. Is this a bug in my code or am I inputting something wrong? For example: const i18nInstance = { options ...

Showing nested array objects in ngx datatable can be achieved by following these steps

Can anyone assist me in extracting object data from a nested array within an ngx datatable column? I have provided an example for reference. Check out this example on StackBlitz ...

Step-by-step guide on deploying an app folder containing both Backend and Frontend folders to Heroku

I recently developed a new app named my-folder-book, which consists of two folders known as my-folder-front and my-folder-back. These folders are built using React and NodeJS. Could someone please assist me with uploading this app folder? I am having trou ...

Assigning values to objects based on the types of their properties in Typescript

In my Redux store, I want to create a reducer that can modify any attribute values within the store. Consider the state object defined with specific types: type StoreState = { admins: Admin[]; messages: Message[]; pageInformation: PageInformation; } ...

Encountering an issue following the upgrade of Angular CLI from 8 to 10

After upgrading my Angular project from version 8 to 10, I encountered an error during compilation. The specific error message is as follows: ERROR in node_modules/ngx-loading/lib/ngx-loading.module.d.ts:4:55 - error TS2314: Generic type 'ModuleWithPr ...

Is there a way to pass around jest mocks across numerous tests?

In my test scenarios, I've created a mock version of the aws-sdk, which is functioning perfectly: jest.mock("aws-sdk", () => { return { Credentials: jest.fn().mockImplementation(() => ({})), Config: jest.fn().mockImplementati ...

The Angular language service is experiencing difficulties in VS Code when it comes to newly created components using the CLI

I am currently facing an issue with the angular language service in an older project that already has a few components created. The problem arises when trying to generate NEW components using the CLI. For instance, a new component generated today: https:/ ...

Ways to pass an @inject constructor parameter using jest

My service includes: @Injectable({ providedIn: 'root', }) export class MyService { constructor(private readonly _http: HttpClient, @Inject('env') private env) {} getData(): Observable<string> { return this._http.get< ...

When closing a Bootstrap modal, the modal overlay does not automatically close along with it

Need assistance with a functionality where new requests can be added and existing requests can be edited using a single component that regenerates with the correct data when needed. Below is the code for the base component: home-component.html <ul c ...

`Understanding the outcome type by assessing the (potential) attributes with TypeScript`

Here is a detailed example of a problem with some code: type Mapper<T, R> = (data: T) => R; interface Config<T, R> { readonly mapper?: Mapper<T, R>; } function transform<T, R>(config: Config<T, R>, data: T) { return c ...

What is the best way to relocate the styles folder to the src folder while using nextjs, typescript, and tailwind

I am currently working with Next.js using TypeScript and Tailwind CSS. My goal is to relocate the styles folder into the src folder. I have already updated the baseUrl in my tsconfig.json file to point to the src directory, but I encountered the following ...

Developing an Observer and sending updates to my followers

I have a function that returns an Observer for subscription. Inside this function, I make an API call which also returns an Observer to which I subscribe. Once I analyze the data received from this Observer, I need to notify my own Observer subscribers. B ...

How can I exclude the 'node_modules' directory but still include specific subfiles in the tsconfig file for TypeScript?

My tsconfig file is structured as follows: { "compileOnSave": false, "compilerOptions": { "module": "es2015", "target": "es2015", "sourceMap": true, "jsx": "react", "allowSyntheticDefaultImports": true, "noImplicitAny": false, ...

Error encountered in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

How to dynamically incorporate methods into a TypeScript class

I'm currently attempting to dynamically inject a method into an external class in TypeScript, but I'm encountering the following error. Error TS2339: Property 'modifyLogger' does not exist on type 'extclass'. Here's the ...

How can Angular provide a visual indication when a component change occurs?

Facing a dilemma as an Angular beginner... Imagine having an application that displays the most recent price of AAPL stock. You have a component where this price is received. Each time you request data from the API, a new price is retrieved and passed to ...

Datatable - pagination - retrieving data from a specific page

Can someone tell me how to retrieve the records from a specific page in a PrimeNG datatable using Angular 2.0? ...

Ensure your Vue components have type-checked props at compile time when using TypeScript

I have encountered an issue while using Vue.js with Typescript. The code I am working with is pretty straightforward, utilizing vue-class-component and vue-property-decorator. <script lang="ts"> import { Component, Prop, Vue } from 'vue-pro ...