2016-05-12 13 views
0

私はAngular 2(RC1)でアプリケーションを構築しようとしています。 UserListComponentとUserDetailComponentの2つのコンポーネントで構成されています。子要素をAngular 2に構築する

アプリケーションは、UserDetailComponentが表示されている場合(テンプレートのmy * ngIf = "selected_user"タグのため)、すべてのユーザーがクリック可能なリスト(この機能はUserListComponentに実装されています)を表示します。

しかし、問題は次のとおりです。UserDetailFormはUserDetailComponentの構築中に作成されますが、最初はユーザーが選択されず、そのためにコードが破損します。これは私のUserDetailComponentです。

import { Component, Input } from '@angular/core'; 
import { FORM_DIRECTIVES, FormBuilder, ControlGroup } from '@angular/common'; 

import { User } from '../classes/user'; 

@Component({ 
    selector: 'user-detail', 
    directives: [FORM_DIRECTIVES], 
    templateUrl: 'partials/user-detail.html', 
}) 

export class UserDetailComponent { 
    userDetailForm: ControlGroup 
    @Input() 
    user: User; 

    constructor(form: FormBuilder) { 
     this.userDetailForm = form.group({ 
      'first_name': [this.user.first_name], 
      'last_name': [this.user.last_name], 
      'email': [this.user.email] 
     }); 
    } 

選択したユーザーが割り当てられている場合にのみ、このコンポーネントを作成する可能性はありますか?また、そのコンポーネントをUserDetailListの子コンポーネントにしておきますか?

編集:要求された私の(簡体字)親コンポーネントとして:

import {Component, OnInit} from '@angular/core'; 

import { User } from '../classes/user'; 
import { UserService } from '../services/user.service'; 
import { UserDetailComponent } from './user-detail.component'; 

@Component({ 
    templateUrl: 'partials/user-list.html', 
    directives: [ UserDetailComponent ] 
}) 

export class UserListComponent { 
    selectedUser: User; 
    users: User[]; 
    number_of_pages: number; 
    currentPage: number; 
    number_of_users: number; 

    constructor(private _userService: UserService) { 
     this.currentPage = 1; 
     this.number_of_pages = 0; 
     this.number_of_users = 0; 
    } 

    getUsers() { 
     this._plugifyService.getUsers().subscribe(data => { 
      this.users = data.users, 
      this.number_of_pages = data.number_of_pages, 
      this.number_of_users = data.number_of_users 
     }); 
    } 

    onSelect(user: User) { 
     this.selectedUser = user; 
    } 

    ngOnInit() { 
     this.getUsers(); 
    } 
} 
+0

を追加してくださいすることができ親のコードとこのコンポーネントの作成方法を教えてください。 –

+0

''が作成された 'user-list.html'の部分も追加してください。 –

答えて

1

あなたはngOnInitフックメソッドでフォームを定義することができます。

constructor(form: FormBuilder) { 
} 

ngOnInit() { 
    this.userDetailForm = form.group({ 
     'first_name': [this.user.first_name], 
     'last_name': [this.user.last_name], 
     'email': [this.user.email] 
    }); 
} 

入力プロパティは、最初の後にのみ使用可能ですngOnInitのコールの直前にngOnChangesメソッドのコールを使用します。

あなたは、この方法を使用することができます

<user-detail *ngIf="selected_user" [user]="selected_user"></user-detail> 
0

値が設定されている場合、あなたがngOnChanges()にコードを移動した場合、それは(再)フォームを作成します。

constructor(private form: FormBuilder) {} 

ngOnChanges() { 
    this.userDetailForm = form.group({ 
     'first_name': [this.user.first_name], 
     'last_name': [this.user.last_name], 
     'email': [this.user.email] 
    }); 
} 
関連する問題