我在select中的列表项迭代问题。
我想要展示的是子组件中的列表项
viewDidDisappear
选择选项
<li
class="list-group-item clearfix"
(click)="onSelected()">
<div class="pull-left">
<h4 class="list-group-item-heading">{{project.name}}</h4>
</div>
</li>
但是下拉列表显示了这两个项目。
重要的是我必须从子组件迭代列表项。
怎么了? Stackblitz
答案 0 :(得分:1)
您正在循环每个项目:
<app-project-item *ngFor="let projectElement of projects"
[project]="projectElement"></app-project-item>
这将导致每个选项都包含所有项目。
我不确定你为什么这样做而不仅仅是:
<option *ngFor="let project of projects">{{project.someLabel}}</option>
答案 1 :(得分:0)
@Corry,您放置的最后一个StackBitz是通过服务公共父母和孩子的示例:https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
因此,您的projectlist.component.html可以像
<select #project (change)="changeProject(project.value)">
<option *ngFor="let projectElement of projects"
[value]="projectElement.id">{{projectElement.name}}</option>
</select>
看看如果选择更改,我们将函数changeProject称为参数,选择项目的“id”
并在projectlist.component.ts
中ngOnInit() {
this.projects = this.projectService.getProjects();
//See that this.projectService.getProject it's NOT an observable
//just the elements. If this function was an observable
// we must subscribe to it
//At first call the function with the first element
this.changeProject(this.projects[0].id);
}
changeProject(value:any)
{
//"emit" a new value in the observable of the service
this.projectService.projectSelected.emit(this.projects.find(d=>d.id==value));
}
无论如何,这是一个“奇怪的”代码。如果你想要两个关系选择(如果元素不多,那么总是如此,你可以简单地
export class ProjectsComponent implements OnInit {
selectedProject: Project;
projects:Project[];
constructor(private projectService: ProjectService) { }
ngOnInit() {
this.projects = this.projectService.getProjects();
this.selectedProject=this.projects[0];
}
}
你的ProjectsComponent .html喜欢
<form>
<select name="project" [(ngModel)]="selectedProject">
<option *ngFor="let projectElement of projects"
[ngValue]="projectElement">{{projectElement.name}}</option>
</select>
<select >
<option *ngFor="let task of selectedProject?.tasks">{{ task.name }}
</option>
</select>
</form>