【发布时间】:2020-05-19 00:24:03
【问题描述】:
我一直在尝试解决这个问题,并尝试了几种来自 stackoverflow 的解决方案,但都没有成功。例如@ViewChild in *ngIf
当我在 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;
}
}
【问题讨论】:
-
@RobinDeSchepper 我也试过了,但没有解决问题。我会将其添加到问题描述中。
-
是的,我看到你链接了它,但为什么它不起作用?您是否尝试将一些控制台日志添加到 setter 以了解 setter 的调用时间?您可以将 ngIf 条件链接到一个按钮,单击它并查看是否打印了某些内容。如果没有,请尝试仅使用 ngIf、ViewChild 和按钮创建一个新项目。
-
我试过了,setter 甚至一开始就没有被调用过。
-
@RobinDeSchepper 我在另一个页面上再次尝试了 setter,它工作正常,所以不确定我的原始代码是什么。
标签: angular