我正在使用*ngFor
显示一些数据,我想从*ngFor
中提取一些值并将其显示在例如标题中。我尝试使用{{ project }}
,但是没有用。每次返回undefined
,但我正在ngOnInit()
内获取数据
我的HTML看起来像:
<div *ngIf="show; else noproject" class="container">
<h1 class="mb-3 text-primary">Virtual machines for {{vms[project]}}</h1>
<button (click)="navigateToDetails(pid)" class="btn btn-success btn-sm mr-2"><i
class="fas fa-plus-circle"></i> Add VM</button>
<button (click)="navigateToDetails(pid)" class="btn btn-primary btn-sm mr-2"><i
class="fas fa-plus-circle"></i> Commit Changes</button>
<table class="table text-center table-hover table-striped">
<thead appBtnd class="bg-primary text-white">
<th appBtn [sortKey]="'name'" [data]="vms">VM Name</th>
<th appBtn [sortKey]="'ipAddress'" [data]="vms">IP Address</th>
<th appBtn [sortNumber]="'diskSize'" [data]="vms">Disk Size</th>
<th appBtn [sortNumber]="'cpu'" [data]="vms">CPU</th>
<th appBtn [sortNumber]="'ram'" [data]="vms">Ram</th>
<th>Gateway</th>
<th>NetMask</th>
<th>Actions</th>
</thead>
<tbody>
<tr *ngFor="let vm of vms">
<td>{{vm.name | titlecase }}</td>
<td>{{vm.ipAddress}}</td>
<td>{{vm.diskSize}}</td>
<td>{{vm.cpu}}</td>
<td>{{vm.ram}}</td>
<td>{{vm.gateway}}</td>
<td>{{vm.netmask}}</td>
<td>
<button class="btn btn-sm btn-danger" type="submit" (click)="deleteVm(vm.id)">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
角度代码:
export class VmForProjectComponent implements OnInit {
vms: ProjectForUser show: boolean; pid: number; constructor(private alertify: AlertifyService, private route: ActivatedRoute, private vmService: VmService, private projectService: ProjectService, private router: Router) { }
ngOnInit() {
const projectId = +this.route.snapshot.paramMap.get('projectId');
this.projectService.getVmByProjectId(projectId).subscribe(p => this.vms = p);
if (this.vms !== null || undefined) { this.show = true; }
}
答案 0 :(得分:0)
您也许可以创建视图子元素ref并在ngAfterViewInit上设置值。请参见下面的代码:
模板:
<input type="hidden" name="cpuTitleName" #cpuTitle value="vm.project" />
<button class="btn btn-sm btn-danger" type="submit" (click)="deleteVm(vm.id)">
i class="fas fa-trash"></i>
</button>
TS:
export class AppComponent implements OnInit, AfterViewInit {...
@ViewChild('cpuTitle', {static: false}) projectEl: ElementRef;
ngAfterViewInit(): void {
this.cpuTitle = this.projectEl.nativeElement.value;
}
全栈闪电战:
https://stackblitz.com/edit/angular-mebigy?file=src%2Fapp%2Fapp.component.html