带有选择器的angular2传递对象

angular2 pass object with selector

我无法将对象从 selector 传递到组件。 我不知道这是否可能。

所以我想要的是 select 下拉列表,其中包含从休息服务中获取的对象。 然后在 select 上,我想在我加载 selector.

的组件中设置对象
        <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 + ")");
        }
    }
}

然后我有select或者像这样:

@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);    
        }
    }

}

和selector.html

     <div>
        <select (change)="select.next(g)">
            <option *ngFor="let g of games" ngValue="g">
                {{g.name}}
            </option>
        </select>
    </div>

我尝试了很多东西,但在这种情况下,大多数情况下我得到的值是 {{g.name}} 或“[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"可以省略。这只是赋初值。