【发布时间】:2021-05-14 18:49:53
【问题描述】:
我想根据我使用 ngFor 指令从选择标记中选择的值以角度显示不同的表格。现在我正在使用一些布尔变量来执行此操作,并且正在使用 html 中的 ngIf 检查条件。您可以参考我的示例代码,如下所示。
这是我的示例代码:
component.html
<select class="form-control" [(ngModel)]="selectOption" (change)="getTables($event)">
<option *ngFor="let item of optionsArr" [value]="item.slectedValue" >{{ item.slectedValue }}
</option>
</select>
<table class="table table-bordered" id="admin-table" *ngIf="adminText">
<thead>
<th>Check Me</th>
<th>Sr. No</th>
<th>ID</th>
<th>Admin Name</th>
<th>City</th>
</thead>
<tbody>
<tr *ngFor="let admin of adminArr; let i = index">
<td><input type="checkbox" name="chk1" id="chk1"></td>
<td>{{ i+1 }}</td>
<td>{{ admin.id }}</td>
<td>{{ admin.name }}</td>
<td>{{ admin.city }}</td>
</tr>
</tbody>
</table>
<table class="table table-bordered" *ngIf="employeeText">
<thead>
<th>Sr. No</th>
<th>ID</th>
<th>Employee Name</th>
<th>City</th>
</thead>
<tbody>
<tr *ngFor="let item of employeeArr; let i = index">
<td>{{i+1}}</td>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.city}}</td>
</tr>
</tbody>
</table>
<table class="table table-bordered" *ngIf="studentText">
<thead>
<th>Sr. No</th>
<th>ID</th>
<th>Student Name</th>
<th>City</th>
</thead>
<tbody>
<tr *ngFor="let item of studentArr; let i = index;">
<td>{{i+1}}</td>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.city}}</td>
</tr>
</tbody>
</table>
组件.ts
adminArr: any = [];
employeeArr: any = [];
studentArr: any = [];
selectOption:any;
adminText: boolean = false;
employeeText: boolean = false;
studentText: boolean = false;
newValue:any;
optionsArr:any = [
{"id": 1, "slectedValue": "Admin"},
{"id": 2, "slectedValue": "Employees"},
{"id": 3, "slectedValue": "Students"}
]
getTables(event: any){
let value = event.target.value;
this.newValue = value;
if(this.newValue === "Admin"){
this.adminText = true;
this.http.get(this.adminUrl).subscribe(data => {
this.adminArr = data;
this.adminArr.push(data);
});
console.log(this.adminArr);
this.employeeText = false;
this.studentText = false;
}
else if(this.newValue === "Employees"){
this.employeeText = true;
this.http.get(this.stdUrl).subscribe(data => {
this.employeeArr = data;
this.employeeArr.push(data);
});
this.adminText = false;
this.studentText = false;
}
else{
this.studentText = true;
this.http.get(this.stdUrl).subscribe(data => {
this.studentArr = data;
this.studentArr.push(data);
});
this.employeeText = false;
this.adminText = false;
}
}
我认为这种方法不合适,因为如果我的选择标签中有 10 个值,那么这不是一个好的编码习惯。 必须有一些更好的方法来做同样的事情。谁能告诉我这样做的正确方法? 谁能帮我找到更好的解决方案?
注意:目前我还没有创建任何模型类和服务。这就是为什么我只在我的组件中使用 http 请求。
【问题讨论】:
标签: angular