Angular 4 offers a variety of template options to choose from

Imagine these divs within a component:

<div ngIf="condition1">   
<button (click)="set_condition1_false_and_2_true()">show-template-2</button> 
</div>

<div ngIf="condition2>   
<button (click)="set_condition2_false_and_3_true()">show-template-3</a> 
</div>

<div ngIf="condition3>   
<a>Last Template</a>
</div>

If the TypeScript is correctly handling the booleans, how can I create this view?

(note) I managed to make it work with two divs:

<div *ngIf="condition1; else secondTemplate>
  <button (click)="make_condition1_false_and_2_true()">showSecondTemplate
</button>
</div>

<ng-template #secondTemplate>
  <a>Second Template Works</a>
</ng-templante> 

However, I need three templates in the same component

Answer №1

If you're looking for a straightforward approach, one way to handle this is by ensuring that the other conditions are false in your *ngIf statements.

Here's an example with just the if statements:

<div *ngIf="!condition2 && !condition3 && condition1">   

<div *ngIf="!condition1 && !condition3 && condition2">   

<div *ngIf="!condition1 && !condition2 && condition3> 

Another option is to utilize NgSwitch. This method works well when all conditions are based on the same variable, but if they're not, you can create a helper function to handle it.

<div [ngSwitch]="getState()">
  <div *ngSwichCase="1">   
  <div *ngSwichCase="2">   
  <div *ngSwichCase="3"> 
</div>

Within your TypeScript code, define the getState function using if/then/else logic like so:

getState() {
  if (condition1) {
    return 1;
  } else if (condition2) {
    return 2;
  } else {
    return 3;
  }
}

In your actual implementation, consider using a more descriptive function name and returning an enumeration value instead of arbitrary numbers.

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

Select a randomly generated number from an array, which dynamically updates every time the browser is refreshed

I recently completed a project in Angular that utilizes the TMDB API. The project is nearly finalized, but I have a desire to implement a change where the background image (backdrop_path) and other elements shift each time the browser is reloaded. Curren ...

React - All subsequent variable declarations must be of the same type

Running webpack in my React application results in the following error message appearing 58 times across different variables: https://i.sstatic.net/uedR7.png Removing the @types directory did not resolve the issue and instead produced a new error message: ...

Tips for mocking Dependent Modules in Jasmine when dealing with a plethora of dependencies in Angular 9

Looking to create a unit test for a component within an Angular project. The main component has 5-6 dependencies and extends another class with around 7 additional dependencies. What is the most effective method to set up the TestBed for this component? ...

Issue with the functionality of Angular reactive custom validator inoperable

Recently, I created a simple validator that compares the values of two date form controls within a form group. The basic rule is that the maturityDate has to be greater than the valueDate, otherwise the form group should be marked as invalid. Here is how ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

Guide on validating a dropdown using template-driven forms in Angular 7

Having trouble validating a dropdown select box, possibly due to a CSS issue. Any suggestions on how to fix this validation problem? Check out the demo here: https://stackblitz.com/edit/angular-7-template-driven-form-validation-qxecdm?file=app%2Fapp.compo ...

Having trouble accessing an injector service within the promise of a dynamically loaded JavaScript function that has been assigned to a global variable

Query I am facing an issue while trying to integrate PayPal with Angular. I am encountering difficulties when attempting to call an injected service inside a function of the promise returned. Any assistance in resolving this would be greatly appreciated. ...

Prevent Angular 4 Component Reloading

I need my component to remain stable without reloading every time a new page is accessed. Currently, it reloads on each page change which disrupts the functionality. This issue is particularly evident in the Header section where there is a Marquee that rel ...

What steps do I need to take in order to develop a custom component for FormControls?

Trying to create a form with a custom component for controls, I encountered an issue. Despite including the new component in the parent form that already has a formGroup, Angular throws an error. The error I faced is: Error: formControlName must be use ...

Ways to initiate update notification when altering an array object?

I am working on my Angular4 app and I have a component that uses a *ngFor directive to iterate over an array: <div *ngFor="let person of persons"> {{person.name}} {{person.car}} </div> Within the same component, there is a feature to ...

Angular error: Attempting to access the value property of an undefined object

When attempting to delete a row from a table, an error occurred stating "TypeError: Cannot read property 'value' of undefined" after placing the delete button at the end of a row. I watched this video tutorial for guidance on deleting a row witho ...

Tips for transferring photos with Angular 5 and Node.js

What is the process for uploading images with angular 5 and node js? ...

Invalid Type Property - Request and Response Express Types

When I try to utilize the Request or Response types in this manner: app.use('*', (req: Request, res: Response, next: NextFunction) => { res.set('Cache-Control', 'no-store'); const requestId: string = req.headers[&a ...

What could be causing my matDialog to display incorrectly in Angular version 15?

After I upgraded my project to version 15 of Angular, following the official Angular documentation, I encountered an issue with my MatDialog not opening correctly. The problem seemed to stem from removing the entryComponents and transforming all components ...

Establishing a response header in conjunction with a specified string

I'm facing an issue while attempting to include a token in the headers of an HTTP request from backend to frontend, along with sending a custom string. Despite my efforts, I am encountering a problem where the token appears as null on the client-side. ...

Unable to post links on Facebook when using Angular 7

Is it possible to share a URL on Facebook using Angular 7 without server-side rendering like Angular Universal or prerender? I attempted to update meta tags for Facebook share during the click function, but it did not work. What is the most effective way t ...

What is the process for clearing cache in inversifyJS?

In my simple application, I am using express server along with TypeScript. Initially, I can successfully reach my endpoint, but after updating the model, the old data persists. I have attempted the suggested approach mentioned here: How to disable webpage ...

Angular 6 and Typescript: How to Map Objects in Arrays within Arrays

We currently have two arrays named speisekarte (consisting of 10 objects) and essensplan (containing 8 objects). const speisekarte = [ { id: 11, name: 'Kabeljaufilet', price: 3.55, type: 'with fish' }, { id: 12, name: 'Spaghet ...

What is the best way to connect a text box to a nested object in the state of a React component?

Solving a React Debugging Dilemma In my current project, I'm developing an office add-in using a React-based starter kit and TypeScript. Unfortunately, debugging has been a challenge as I am unable to access detailed error messages from React in my s ...

Tips for deactivating the matMenuTrigger when the mat menu does not display any menu items

How can I dynamically disable the mat menu trigger when no items are rendered due to ngIf conditions in the mat-menu? <button mat-button [matMenuTriggerFor]="menu" [disabled]="disableTrigger" > Trigger </button> <mat-menu #menu ...