我有2个JSON文件,分别基于contacts
JSON中的workers
,分别称为workersId
和contacts
,我正在循环并显示特定联系人的工作人员,如下所示:
现在,我正试图在单行中显示workers objects
,如下所示:
我在 P 标记中显示worker对象,我给cs的名称为display:inline;
,但它不在同一行显示:
下面是组件代码:
HTML
<h4>Contacts</h4>
<div class="cust-detail" *ngFor="let contact of contacts">
<p><span><b>Name:</b></span> {{contact.name }}</p>
<span><b>Assigned Workers</b></span>
<div *ngFor="let workerId of contact.workers">
<p class="workers">
{{getWorkerById(workerId)}}
</p>
</div>
<hr>
</div>
TS
import { Component } from '@angular/core';
import { ContactService } from './contacts.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
contacts;
workers;
constructor(private myService: ContactService) {}
ngOnInit() {
this.myService.getContacts()
.subscribe(res => this.contacts = res);
this.myService.getWorkers()
.subscribe(res => this.workers = res);
}
getWorkerById(workerId) {
if (this.workers && this.workers.length > 0) {
for(let w of this.workers) {
if(w.id === workerId)
return w.name;
}
}
}
}
CSS
.workers{
display:inline;
}
答案 0 :(得分:1)
尝试使用HTML
<h4>Contacts</h4>
<div class="cust-detail" *ngFor="let contact of contacts">
<p><span><b>Name:</b></span> {{contact.name }}</p>
<p><b>Assigned Workers</b></p>
<span *ngFor="let workerId of contact.workers">
<p class="workers">
{{getWorkerById(workerId)}}
</p>
</span>
<hr>
</div>
答案 1 :(得分:1)
您需要按以下方式更改HTML和CSS
<h4>Contacts</h4>
<div class="cust-detail" *ngFor="let contact of contacts">
<p><span><b>Name:</b></span> {{contact.name }}</p>
<span><b>Assigned Workers</b></span>
<div class="all-workers">
<div *ngFor="let workerId of contact.workers">
<p class="workers">
{{getWorkerById(workerId)}}
</p>
</div>
</div>
<hr>
</div>
和css
.all-workers{
display: flex;
}
答案 2 :(得分:1)
尝试这个以发表新评论
<h4>Contacts</h4>
<div class="cust-detail" *ngFor="let contact of contacts; let i = index">
<tr>
<td>Name</td>
<td>{{contact.name }}</td>
</tr>
<tr>
<td>Assigned Workers</td>
<td>
<div [ngClass]="{'all-workers' : showmore[i]==false }">
<div *ngFor="let workerId of contact.workers;let j=index">
<p class="workers" *ngIf="(showmore[i]==false &&j<=1)||showmore[i]==true">
{{getWorkerById(workerId)}},
</p>
</div>
</div>
<button *ngIf="contact.workers.length>2" (click)="showmore[i]=!showmore[i]">{{(showmore[i])?"Show less":"Show more"}}</button>
</td>
</tr>
<hr>
</div>
答案 3 :(得分:0)