繁体   English   中英

@ViewChild 对表单的引用在带有 *ngIf 的 Angular 中未定义

[英]@ViewChild reference to form is undefined in Angular with *ngIf

我一直在尝试解决这个问题,并尝试了几种来自 stackoverflow 的解决方案,但都没有成功。 例如*ngIf 中的 @ViewChild

当我在 init 上加载客户时它工作正常,但现在我订阅了用户和客户,这导致了问题。

当我单击保存按钮(从表单外部)触发表单 onSubmit 时,它不起作用,因为 formCustomerDetailsRef 未定义,即使我有一个有效的客户并且我可以看到表单。

我也尝试过使用 changeDetector.detectChanges(); 和 ngZone 但是这些并没有帮助。

我尝试了以下技术,但它也不起作用: https://stackoverflow.com/a/41095677/10222449

我正在使用 Angular 8。

 export class HomeComponent implements OnInit, OnDestroy { @ViewChild('formCustomerCtrl', { static: false }) formCustomerDetailsRef: FormGroupDirective; ... ngOnInit(): void { const sub = this.authService.currentAppUser$.subscribe(appUser => { this.appUser = appUser; if (appUser) { this.getCustomer(); this.getSettings(); this.getCountries(); } }... getCustomer() { const sub = this.customerService.currentCustomer$.subscribe(async customer => { this.customer = customer; ... onSubmitCustomerForm() { this.formCustomerDetailsRef.onSubmit(undefined); }
 <ng-container *ngIf="customer"> <div *ngIf="fbUserAuthClaims?.admin" class="button btn_2" (click)="onSubmitCustomerForm()"> <img src="assets/icons/link.svg">Save Changes </div>... <article *ngIf="tabCompanyProfileSelected"> <form *ngIf="customer" [formGroup]="formCustomerDetails" (ngSubmit)="onUpdateCustomer()" #formCustomerCtrl="ngForm">...

也不起作用的替代代码:

 private formCustomerDetailsRef: FormGroupDirective; @ViewChild('formCustomerCtrl', { static: false }) set content(content: FormGroupDirective) { if (content) { // initially setter gets called with undefined this.formCustomerDetailsRef = content; } }

正如@Robin 在评论中指出的那样,解决方案是使用 setter。

这里的解决方案:

https://stackoverflow.com/a/41095677/10222449

只要记住设置 static = false。

https://stackoverflow.com/a/57508471/10222449

例子:

 addressElementRef: ElementRef; @ViewChild('address', { static: false }) set content(content: ElementRef) { if (content) { // initially setter gets called with undefined this.addressElementRef = content; } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM