angular2传递带有选择器的对象

时间:2016-06-02 13:10:43

标签: javascript jquery angular angular2-services truecrypt

我遇到一个问题,我无法将对象从选择器传递给组件。 我不知道这是否可能。

所以我想要的是从休息服务中获取对象的选择下拉列表。 然后在选择我想在我加载选择器的组件内设置对象。

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

}

和selector.html

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

我尝试了很多东西,但大多数情况下我得到的值是{{g.name}} oder&#34; [object Object]&#34;作为输出。

但我希望将整个对象传递给组件。

有任何想法如何完成这项工作?

亲切的问候

1 个答案:

答案 0 :(得分:1)

ngValue="g"可能无法达到您的预期。它会在<option>上创建一个属性值为&#39;&#34; g&#34;&#39;。要进行Angular处理,需要[]{{}}(仅限字符串)。

我非常确定您还需要使用[(ngModel)](ngModelChange)来获取所选值。

   <select [ngModel]="someProp" (ngModelChange)="select.next($event)">
        <option *ngFor="let g of games" [ngValue]="g">
            {{g.name}}
        </option>
    </select>

[ngModel]="someProp"可以省略。这只是为了分配一个初始值。