我有一个问题,我无法将对象从选择器传递给组件。我不知道这是否可能。
所以我想要的是一个选择下拉列表,其中包含从休息服务获取的对象。然后在选择时,我想在加载选择器的组件中设置对象。
<div class="col-md-12">
<div class="col-md-4">
<game-selector [customers]="customers" [(selected)]="selectedGameSize" (select)="onItemSelected($event)"></game-selector>
</div>
</div>
<div class="col-md-12" [gameSize]="selectedGameSize">
<div class="col-md-4" *ngIf="gameSize">
{{gameSize | json}}
</div>
</div>
TS 文件:
@Component({
selector: 'fleet',
templateUrl: 'app/fleet/fleet.html',
directives: [CORE_DIRECTIVES, ROUTER_DIRECTIVES, GameSizeSelector, FactionSelector]
})
export class FleetComponent {
@Output() select = new EventEmitter();
selectedGameSize: GameSize;
constructor() { }
@Input() gameSize: GameSize;
ngOnInit(){
}
onItemSelected(selectedItem: GameSize){
if (this.gameSize == null) {
} else {
console.log("onItemSelected(" + this.gameSize.name + ")");
}
}
}
然后我有这样的选择器:
@Component({
selector: 'game-selector',
templateUrl: 'app/selector/gameSelector.html',
providers: [GameSizeService]
})
export class GameSizeSelector implements OnInit {
@Output() select: EventEmitter<GameSize> = new EventEmitter();
@Input() games: GameSize[] = [];
@Output() gameSize: GameSize;
@Input() selected: GameSize;
constructor(
private gameService: GameSizeService) {};
getGames() {
this.gameService
.getGameSizes()
.then(games => this.games = games);
}
ngOnInit(){
this.getGames();
if (this.games == null) {
} else {
this.select.emit(this.gameSize);
}
}
}
和选择器.html
<div>
<select (change)="select.next(g)">
<option *ngFor="let g of games" ngValue="g">
{{g.name}}
</option>
</select>
</div>
我尝试了很多东西,但大多数情况下我得到的值在这种情况下 {{g.name}} oder "[object Object]" 作为输出。
但是我希望将整个对象传递给组件。
任何想法如何完成这项工作?
亲切问候
ngValue="g"
可能不会达到您的预期。它在<option>
上创建一个值为"g"的属性。要使Angular处理它需要[]
或{{}}
(仅字符串)。
我很确定您还需要使用[(ngModel)]
或(ngModelChange)
来获取所选值。
<select [ngModel]="someProp" (ngModelChange)="select.next($event)">
<option *ngFor="let g of games" [ngValue]="g">
{{g.name}}
</option>
</select>
[ngModel]="someProp"
可以省略。这只是为了分配一个初始值。