Let's supose, i have following components:
@Component({
selector: '.abc',
template: '{{ message }}'
})
export class AbcComponent {
@Input() message: string;
}
@Component({
selector: '.efg',
template: '{{ message }}'
})
export class EfgComponent {
@Input() message: string;
}
@Component({
selector: 'my-wrapper',
templateUrl: './my-wrapper.component.html'
})
export class MyWrapperComponent implements OnInit {
data: { selector: string, message: string }[];
ngOnInit() {
data = [
{selector: 'abc', message: 'Hello '},
{selector: 'efg', message: 'world'}
];
}
}
and my-wrapper.component.html
<div class="abc" [message]="Hello "></div>
<div class="efg" [message]="World"></div>
Because AbcComponent and DefComponent selectors are prefixed with dot, i can select component using class parameter.
And here comes the question. Can i set that class dynamically? I will now use a data field of MyWrapperComponent and change my-wrapper.component.html to:
<div *ngFor="let element of data">
<div [class]="element.selector" [message]="element.message"></div>
</div>
Unfortunatelly, that won't work and error message is message is not known property of div. But even if i remove that property binding, it renders div with attached class, instead of component.
I tried also with class="{{element.selector}}" and [ngClass]="element.selector" but in both cases, it's not working.
Workaround for this could be ngSwitch.
<div *ngFor="let element of data" [ngSwitch]="element.selector">
<div class="abc" *ngSwitchCase="'abc'" [message]="element.message"></div>
<div class="def" *ngSwitchCase="'def'" [message]="element.message"></div>
</div>
But i don't like that solution because there's a code duplication and i want it more dynamically.
Described components are dummy, my use case is to create a generic navigation component, that recives list of element's representing existing components of type
{selector: string, data: any}
and based on that, it displays components dynamically e.g.RouterLinkNavigationItemComponent, ExternalLinkNavigationItemComponent, AnchorNavigationElement and so on.