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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With