【发布时间】:2018-08-24 02:50:21
【问题描述】:
我在 Angular 2 中创建了一个表单,用户可以使用该表单编辑 SearchProfile,他们可以从列表中进行选择。最初一切正常,但是当我从SearchProfiles 列表中选择不同的项目时,我收到以下异常:
There is no FormControl instance attached to form control element with name: controlName。
整个事情由 3 个元素组成:2 个组件SelectProfileComponent、SearchProfileComponent 和一个服务ProfileService。 ProfileService 包含 ActiveProfile,这是选定的 SearchProfile 进行编辑。
ProfileService 看起来像这样:
@Injectable()
export class ProfileService {
private activeProfileSource = new ReplaySubject<ISearchProfile>();
activeProfile$ = this.activeProfileSource.asObservable();
constructor(private http: Http) {
this.selectProfile();
}
public getSearchProfile(profileId: number = null): Observable<ISearchProfile> {
let url = `<url>?profileid=${profileId}`;
this.http.get(url).map((result) => {
return <ISearchProfile>.result.json();
});
}
public selectProfile(profileId: number = null) {
this.getSearchProfile(profileId).subscribe((p) => {
this.activeProfileSource.next(p);
});
}
}
SelectProfileComponent 包含一个带有配置文件的列表,该配置文件在选择 SearchProfile 时触发 change 事件。
<select (change)="setActiveProfile($event.target.value)">
<option *ngFor="let profile of profiles" [value]="profile.Id" [innerHtml]="profile.name"></option>
</select>
export class ProfileSelectionComponent implements OnInit {
private profiles: ISearchProfile[] = null;
constructor(private profileService: ProfileService) {}
//get profiles logic
public setActiveProfile(profileId: number): void {
this.profileService.selectProfile(profileId);
}
}
SearchProfileComponent 与activeProfile 之间有一个Subscription,并且应该显示activeProfile 的属性,以便用户可以编辑它们。
SearchProfileComponent 看起来像这样:
<form [formGroup]="profileForm" *ngIf="!isLoading">
<input type="text" name="name" formControlName="name" [(ngModel)]="searchProfile.name" />
</form>
export class SearchProfileComponent implements OnInit {
private isLoading: boolean = true;
private activeProfileSubscription: Subscription;
private searchProfile: ISearchProfile = null;
public profileForm: FormGroup;
constructor(private profilService: ProfileService
private formBuilder: FormBuilder) { }
ngOnInit() {
this.activeProfileSubscription = this.profileService.activeProfile$.subscribe((profile: ISearchProfile) => {
this.searchProfile = profile;
this.createForm();
this.isLoading = false;
});
}
private createForm() {
this.profileForm = this.formBuilder.group({
["name"]: [this.searchProfile.name, null]
});
}
}
【问题讨论】: