"Concealing and Substituting a Component in Angular 2: A Comprehensive

Hi there! I am currently working on a parent component (A) that contains two child components (B and C). Initially, parent component A is set to display child component B. However, I want to replace child component B with child component C when a button within parent component A is clicked. Can someone guide me on how to achieve this in Angular 2?

Answer №1

If you want to achieve that, you have two options: the *ngIf directive or the hidden property.

Take note of the distinction:

  • *ngIf removes and recreates the element:

When the expression assigned to ngIf evaluates to false, the element is removed from the DOM; otherwise, a clone of the element is reinserted into the DOM.

  • hidden hides the element using display: none

According to angular's documentation:

The show/hide technique is probably fine for small element trees. We should be wary when hiding large trees; NgIf may be the safer choice. Always measure before leaping to conclusions.

Take a look at the example below:

@Component({
  selector: 'my-app',
  template: `
    <b>Using *ngIf:</b>
    <div *ngIf="!isOn">Light Off</div>
    <div *ngIf="isOn">Light On</div>
    <br />
    <b>Using [hidden]:</b>
    <div [hidden]="isOn">Light Off</div>
    <div [hidden]="!isOn">Light On</div>
    <br />
    <button (click)="setState()">{{ getButtonText() }}</button>
  `
})
export class AppComponent {

  private isOn: boolean = false;

  getButtonText(): string {
    return `Switch ${ this.isOn ? 'Off' : 'On' }`;
  }
  setState(): void {
    this.isOn = !this.isOn;
  }

}

Plunker: http://plnkr.co/edit/7b1eWgSHiM1QV6vDUAB0

For more information on [hidden], I recommend reading this article:

I hope this explanation helps.

Answer №2

In the template of Parent A, it is common to have both components included, but to control their visibility using an ngIf directive.

<button (click)="setButtonClicked(true)">Click Me</button>
<component-b *ngIf="!buttonWasClicked"></component-b>
<component-c *ngIf="buttonWasClicked"></component-c>

The model for Parent A would include code like this to manage the property:

buttonWasClicked: boolean = false;

setButtonClicked(clicked: boolean) {
    this.buttonWasClicked = clicked;
}

Alternatively, you might consider using NgSwitch instead of NgIf.

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

Incorporating ng2-bootstrap into an Angular2 project with SystemJS starter template

I am attempting to integrate the ng2-bootstrap modal functionality into a component of my project that is built using the angular2-starter. Below is my systemjs.conf.js configuration: /* * This config is only used during development and build phase onl ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

Adding a variable to this property in real-time

Is there a way to dynamically pass the item variable into this property? For example, if the item has a value of 35, is it possible for it to become this.BookingConfirmationFormsState35? onChange( event, item ){ console.log( this.BookingConfirmationF ...

*ngFor is not rendering

I understand that this question is frequently asked, but the usual solutions don't seem to be effective in this case. Here is my code snippet: export class CourseReviewFormComponent implements OnInit { form: FormGroup questionnaire: string[] = [] ...

Transforming React js into typescript by incorporating data into constants and interfaces

Recently, I've delved into working on React Typescript and embarked on creating a dropdown component using Semantic UI. While Semantic UI offers code in JavaScript format that is easier to comprehend, I encountered a roadblock when attempting to conve ...

Managing the dispatch of a successful action in a component

In my component, I have a form that adds items to a list. Once an item is successfully added, I want to reset the form using form.resetForm();. However, I am struggling to determine when the action of adding the item has been successful. I attempted to sub ...

The Angular Material table does not adapt to different screen sizes

I developed an Angular application using Angular Material that features a table with 22 columns. However, when I expand the browser window, some columns are hidden. Additionally, on mobile browsers, not all columns are displayed. I have attempted the follo ...

Creating an array of input data for component, implementing data formatting in TypeScript for Angular or React applications

Here is an example of the input for the component. When this input is passed to the component, the output displays correctly. const data = [ ['Rank', 'Player', 'Player', 'Player'], ['1& ...

I successfully created a basic application using Ionic and Angular. Is there a way to generate an APK file with Capacitor without relying on Android Studio?

Is it feasible to create an apk file in Ionic without relying on Android Studio? If so, what is the process for doing that using only Capacitor? ...

Running lint-staged on an Angular monorepo

I am facing challenges while setting up lint-staged in my Angular monorepo workspace. Despite multiple attempts, I have been unsuccessful in making it work properly. When the command ng lint --files is executed with a changed file, an error stating that *f ...

Indexes in Typescript objects are used to access specific values

While Typescript has been mostly smooth sailing for me, I keep encountering a roadblock. Let's say I have a type that can be one of several strings: type ResourceConstant = 'A' | 'B' | 'C'; Now I want to create an objec ...

Confirm the Keycloak token by checking it against two separate URLs

In my system, I have a setup based on Docker compose with back-end and front-end components. The back-end is developed using Python Flask and runs in multiple docker containers, while the front-end is coded in TypeScript with Angular. Communication between ...

Ways to display all utilized typescript types within a project

Here is a snippet of code I'm working with in my project: describe('Feature active', () => { it('Should render a Feature', () => { const wrapper = shallow(<MyComponent prop1={1}/>); expect(wrapper.prop('p ...

There was an unexpected error: Module 'restore-cursor' not found

Has anyone else encountered this specific problem with Angular 11 while using ng serve? The issue stems from the following stack trace: C:\Users\x\Desktop\codebase\app\node_modules\cli-cursor\index.js C:\User ...

Launching an Angular 13 application from the local file system may result in startup issues

I am currently dealing with a touch screen controller known as Crestron TS-1070, which is tasked with running an Angular project directly from its local file system. In the past, I have successfully run projects up to Angular 12.x by simply setting the Ba ...

Is it possible to synchronize the Lit cached DOM with the live DOM?

Utilizing the Lit framework for constructing my front-end UI components has been a game-changer. However, I have encountered an issue while incorporating our internal company design system's web components. One of these components has the ability to r ...

I noticed that the ./src/main.js file is present in multi (webpack)-dev-server/client, but unfortunately I do not have the main.js file. I am

I'm currently working on a Vue.js 3 application demo using tailwind and typescript. Each time I try to run the app, I encounter an error message that says: This relative module was not found: * ./src/main.js in multi (webpack)-dev-server/client?https ...

Personalized dot shapes on a line graph with Rechart

I found a helpful resource for customizing dot shapes in line charts at In my chart, I have four lines and I want each line to have a different shape for its data points. I tried implementing the SVG shapes provided in the link, but I need shapes like ci ...

Experience Next.js 13 with Chakra UI where you can enjoy Dark Mode without the annoying White Screen Flash or FOUC (flash of unstyled content)

Upon refreshing the page in my Next.js 13 /app folder application using Chakra UI, I notice a few things: A momentary white flash appears before switching to the dark theme. The internationalization and font settings momentarily revert to default before l ...

Determining the presence of a class while a tab is active using Cypress.io

Looking for a way to determine if Test1 or Test2 has been clicked in the HTML code below: <div> <li><a class="class1 active">Test1</a></li> <li><a class="class1">Test2</a></li> < ...