gpt4 book ai didi

angular - 没有 FormControl 实例附加到具有名称的表单控件元素

转载 作者:行者123 更新时间:2023-12-01 07:02:00 25 4
gpt4 key购买 nike

我在 Angular 2 中创建了一个表单,用户可以用它来编辑 SearchProfile他们可以从列表中选择。最初一切正常,但是当我从 SearchProfile 列表中选择不同的项目时■ 我收到以下异常: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包含一个带有触发 change 的配置文件的列表-事件发生时 SearchProfile被选中。
<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有一个 SubscriptionactiveProfile并且应该显示 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]
});
}
}

最佳答案

我是这样解决的:

前:

formControlName="description"

后:
[formControl]="form.controls['description']"

关于angular - 没有 FormControl 实例附加到具有名称的表单控件元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49296983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com