我正在尝试在Angular 2(RC1)中构建一个应用程序,它具有一个基本形式,使用户可以更改某些值。它由2个组件组成,UserListComponent和UserDetailComponent。
应用程序显示一个列表(该功能在UserListComponent中实现),其中所有用户都是可点击的,如果选择了用户,则显示UserDetailComponent(因为我的* ngIf =" selected_user"模板中的标签)。
然而问题如下: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 :(得分: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]
});
}
输入属性仅在调用ngOnChanges
之前第一次调用ngOnInit
方法后才可用。
然后你可以这样使用:
<user-detail *ngIf="selected_user" [user]="selected_user"></user-detail>
答案 1 :(得分: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]
});
}