2016-11-17 9 views
1

現在、私のドロップダウンにはすべてのユーザーのすべての投稿が表示されていますが、デフォルトでは "leanne Graham"というuser.id 1のユーザーのみを表示します。すべての投稿をデフォルトで表示するのではなく、ユーザーID 1をデフォルトにする方法最初のオプションをデフォルトにして、すべてのユーザーのすべての投稿をデフォルトで表示しないように、コードを調整するにはどうすればよいですか?オプションドロップダウンのデフォルト値を設定する

usercomments.component.ts

<select class="form-control" (change)="reloadPosts({userId: u.value})" #u> 
    <option value="">Select a user...</option> 
    <option *ngFor="let user of users" value="{{user.id}}"> 

    {{user.name}}</option> 

    </select> 



<div class="container"> 


    <table class="table table-bordered"> 

    <tbody *ngFor="let post of _posts"> 
     <tr> 
     <td>{{post.body}}</td> 
     <td>k</td> 
     <td>k</td> 
     </tr> 

    </tbody> 
    </table> 
</div> 

usercomments.component.ts

import { Component, OnInit } from '@angular/core'; 
import {UserPostService} from './userpost.service'; 
import {UserService} from '../users/user.service'; 
@Component({ 
    selector: 'app-usercomments', 
    templateUrl: './usercomments.component.html', 
    styleUrls: ['./usercomments.component.css'], 
    providers: [UserPostService, UserService] 
}) 
export class UsercommentsComponent implements OnInit { 
private _posts; 
users = []; 
private selectedId; 

postLoading; 
private currentPost; 
    constructor(private _userPostService: UserPostService, private _userService:UserService) { 
    } 

    ngOnInit() { 
    this.selectedId= this.users[1]; 
this._userService.getUsers() 
.subscribe(users => this.users = users); 
this.loadPosts(); 
    } 
    loadPosts(filter?){ 

    this.postLoading = true; 
    this._userPostService.getPosts(filter) 
    .subscribe(res => { 
    this._posts = res; 

    }) 

    } 
reloadPosts(filter){ 

this.currentPost = null; 

this.loadPosts(filter); 
} 
} 

答えて

1

使用ngModel

<select [ngModel]="selectedId" class="form-control" 

とあなたが選択しているしたいアイテムのIDを割り当てselectedIdの場合、select要素はこの項目を選択済みとして表示します。

また、代わりにuser.iduserオブジェクトのインスタンスを使用することができますが、あなたは[ngValue]="user"を使用して[ngModel]="selected" gets one of the instance from users`でselectedが割り当てられていることを確認する必要があります。

+0

あなたが選択したいアイテムのIDを割り当てると言うと、