在Angular 2中构造子组件
问题描述:
我正在尝试在具有基本窗体的Angular 2(RC1)中构建应用程序,该窗体使用户可以更改某些值。它由2个组件组成,UserListComponent和UserDetailComponent。在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();
}
}
答
你可以在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>
答
如果你的代码移到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]
});
}
能否请你加入父母的代码以及如何创建此组件? –
请同时添加'user-list.html'的部分,其中''创建。 –