当用户单击菜单以显示组件时,我想在HTML上创建一种方法。我可以单击菜单并显示选择器,但是Angular从不调用会显示我的选择器。我决定对一个类使用div来选择它,但是它得到了构建,但是不起作用。当我对选择器进行硬编码时,它确实起作用,但是当我从<div class="app-{{myVariable}}"></div>
之类的打字稿中调用选择器时,它就无法工作。我不确定为什么这不起作用,还有什么更好的方法。
我从JSON API获得此菜单,例如:
[
{
"selectorName": "employee-details",
"name": "EMPLOYEE DETAILS"
},
{
"selectorName": "employee-training",
"name": "EMPLOYEE TRAINING"
},
]
html父组件
<table *ngFor="let key of menuDataKeys">
<tr>
<td (click)="clicked(menuData[key]['selectorName'])">{{ menuData[key]['name']}}</td>
</tr>
<table *ngIf="contains(menuData[key]['selectorName'])">
<tr>
<!-- I CANNOT MAKE THIS PART WORK! The class name I am using as a selector gets added correctly, but is not treated as a component selector -->
<td><div class="app-{{menuData[key]['selectorName']}}"></div></td>
</tr>
</table>
</table>
打字稿父级组件
ngOnInit() { // I grab the data and I store the keys to be able to loop on the array of hashes
this.http
.get('/myapi/mymenu.json')
.subscribe(data =>{
this.menuData = data;
this.menuDataKeys = Object.keys(data);
}, err =>{
console.log('error')
});
}
clicked(clicked: string) {
// Check if the item has already been clicked and if it is not add to array
// else remove from array
if (this.componentClicked.indexOf(clicked) === -1) {
this.componentClicked.push(clicked);
} else {
this.componentClicked.splice(this.componentClicked.indexOf(clicked), 1);
}
}
// check if item it is in the array and display it
contains(str): boolean{
return this.componentClicked.indexOf(str) !== -1;
}
子打字稿组件
import { Component, OnInit } from '@angular/core';
@Component({
selector: '.app-employee-details',
template: '<h1>HELLO FROM EMPLOYEE DETAILS</h1>',
styleUrls: ['./employee-details.component.css']
})
export class EmployeeDetailsComponent implements OnInit {
constructor() { }
ngOnInit() {
console.log('HELLO FROM EMPLOYEE DETAILS TYPESCRIPT')
}
}