我有一个嵌入了几个子组件的主窗体。 主要表单组件使用服务和主题订阅从API服务器获取数据:
Main.component.ts
@Component({
selector: 'zorg',
templateUrl: './zorg.component.html',
styleUrls: ['./zorg.component.scss']
})
export class ZorgComponent implements OnInit, OnDestroy {
@ViewChild(FooComponent) FooComp: FooComponent;
@ViewChild(BarrComponent) BarComp: QuoteLaBarrComponentyerComponent;
destroy$: Subject<boolean> = new Subject<boolean>();
mandatObjSubscription: Subscription;
mandatoryObjects: {....}={...};
constructor(
private formBuilder: FormBuilder,
private zorgService: QuoteService,
...
) { }
ngOnInit() {
this.initForm();
this.mandatObjSubscription=this.zorgService.mandatObjSubject$.takeUntil(this.destroy$).subscribe(
(data)=> {
this.mandatoryObjects=data;
console.log('OBJ RECEVIED');
console.log(JSON.stringify(this.mandatoryObjects));
},
(error) => {
},
);
var ZorgId;
this.zorgIdSubscription = this.activatedRoute.paramMap.pipe(
map((params: ParamMap) => +params.get('id')),
tap(zorgId => {
//API REQUEST IS MADE HERE
this.zorgService.getMandatoryObjectsFromRest();
}),
filter(zorgId => !!zorgId),
tap(zorgId => ZorgId=zorgId),
...
).takeUntil(this.destroy$).subscribe();
}
initForm() {
this.zorgForm = this.formBuilder.group({
id: '',
label: ['', [Validators.required]],
foo: new FormControl('', [Validators.required, SelectedValue]),
bar: new FormControl('', [Validators.required]),
});
}
我的子组件也需要访问这些数据,因此,我订阅了同一主题。
Foo.compoenent.ts
// describes what the return value of the form control will look like
export interface fooFormValues {
...
}
@Component({
selector: 'ngx-foo,
templateUrl: './foo.component.html',
styleUrls: ['./foo.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => FooComponent),
multi: true
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => FooComponent),
multi: true
}
]
})
export class FooComponent implements OnInit, OnDestroy, ControlValueAccessor {
@Input() inEntityName: string;
@Input() inErrors: any[];
destroy$: Subject<boolean> = new Subject<boolean>();
mandatObjSubscription: Subscription;
mandatObjs;
fooForm: FormGroup;
constructor(
private formBuilder: FormBuilder,
private zorgService: ZorgService,
...
) {
console.log('FOOCONSTRUCT');
}
ngOnInit(): void {
this.entityName= this.inEntityName;
console.log('FOO INTI');
this.initForm();
this.mandatObjSubscription=this.zorgService.mandatObjSubject$.takeUntil(this.destroy$).subscribe(
objects => {
this.mandatObjs=objects[this.entityName];
console.log('OBJMISC RECEIVED');
}
);
this.fooForm.valueChanges.takeUntil(this.destroy$).subscribe(value => {
this.onChange(value);
this.onTouched();
});
}
当我遇到非现值错误时,我添加了consol.log来跟踪问题,并注意到在强制接收对象之后,我的一些子组件已初始化...
我该如何解决?
感谢您的帮助
编辑1:
这是将子组件Foo插入主模板的方式:
<ngx-foo *ngIf="mandatoryObjects.foos.length > 0" id="fooComp" formControlName="foo" inEntityName="foo" [inErrors]="">
</ngx-foo>