Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a component through the id is stored in variable?

I have two components. 1. App component, 2. child component.

For better understanding, the code and output is here in stackblitz: https://stackblitz.com/edit/angular-j9cwzl

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <div id="child"></div>
    <div id="{{childComponent}}"></div>
  `
})
export class AppComponent  {
  childComponent='child';
}

child.component.ts

import { Component } from '@angular/core';

@Component({
  selector: '[id=child]',
  template: '<div>I am child</div>'
})
export class ChildComponent  { }

When I write the id of the child component directly in the template of the App component it renders nicely. but when I write the id of the child component through a variable, it just creates a div element with an id="child".

My question is Why does this happen? How can I render the child with id through a variable in the script file dynamically?

like image 647
Samiul Alam Avatar asked Oct 31 '19 12:10

Samiul Alam


1 Answers

I have a suggestion why your interpolation {{ childComponent }} is not working. In my view, Angular works something in the following order:

  • At first, it sees all your HTML and then tries to find attributes or selectors which can be evaluated as component or directive

  • Then the second step is when we found a component or directive, then {{ }} interpolation is applied

So maybe it is reason why your interpolation is not evaluated in your selector. Because evaluation of selectors are completed and then evaluation of directives started.

If you want to make a decision what component should be rendered, then you can use *ngIf statement:

<ng-container *ngIf="childComponentl else anotherComponent">
    <div id="child"></div>
</ng-container>    
<ng-template #anotherComponent>
    test
</ng-template>

TypeScript:

childComponent='"child1"';

UPDATE:

If you want to avoid hard code, then you can load component dynamically:

  • Dynamically add components to the DOM with Angular
  • Angular 2.1.0 create child component on the fly, dynamically
  • Insert a dynamic component as child of a container in the DOM
like image 165
StepUp Avatar answered Sep 22 '22 21:09

StepUp