[英]@ViewChild reference to form is undefined in Angular with *ngIf
I have been trying to resolve this for a while and have tried several solutions from stackoverflow with no luck.我一直在尝试解决这个问题,并尝试了几种来自 stackoverflow 的解决方案,但都没有成功。 eg @ViewChild in *ngIf例如*ngIf 中的 @ViewChild
It was working ok when I loaded the customer on init but now I subscribe to the user and customer and this is causing problems.当我在 init 上加载客户时它工作正常,但现在我订阅了用户和客户,这导致了问题。
When I click the save button (from outside the form) to trigger the form onSubmit it does not work as formCustomerDetailsRef is undefined even if I have a valid customer and I can see the form.当我单击保存按钮(从表单外部)触发表单 onSubmit 时,它不起作用,因为 formCustomerDetailsRef 未定义,即使我有一个有效的客户并且我可以看到表单。
I have also tried using changeDetector.detectChanges();我也尝试过使用 changeDetector.detectChanges(); and ngZone however these did not help.和 ngZone 但是这些并没有帮助。
I tried the following technique but it did not work either: https://stackoverflow.com/a/41095677/10222449我尝试了以下技术,但它也不起作用: https://stackoverflow.com/a/41095677/10222449
I am using Angular 8.我正在使用 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">...
Alternative code which also does not work:也不起作用的替代代码:
private formCustomerDetailsRef: FormGroupDirective; @ViewChild('formCustomerCtrl', { static: false }) set content(content: FormGroupDirective) { if (content) { // initially setter gets called with undefined this.formCustomerDetailsRef = content; } }
As @Robin pointed out in the comments the solution is to use a setter.正如@Robin 在评论中指出的那样,解决方案是使用 setter。
Solution here:这里的解决方案:
https://stackoverflow.com/a/41095677/10222449 https://stackoverflow.com/a/41095677/10222449
Just remember to set static = false.只要记住设置 static = false。
https://stackoverflow.com/a/57508471/10222449 https://stackoverflow.com/a/57508471/10222449
Example:例子:
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.