angular 10アプリにテンプレート駆動のフォームがあり、変更をリッスンして、「変更されました。更新を送信してください」というメッセージをユーザーに表示できるようにしています。
HTML
<form (ngSubmit)="submit()" class="form-horizontal" #opportunityForm="ngForm">
...
機会.component.ts
export class OpportunityComponent implements OnInit {
@ViewChild('opportunityForm') ngForm: NgForm;
ngOnInit(): void {
...
this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(x => {
console.log(x);
})
しかし、次のエラーが発生します。
TypeError: Cannot read property 'form' of undefined
ngForm が初期化されていないためです。これは同様の質問です: https://ng-run.com/edit/CGoUiw88N7OmI7x0YmHJで同じ問題を抱えている実行中の回答がある、角度のあるテンプレート駆動のフォーム変更をリッスンする方法。
フォームを取得して、変更をリッスンする前にフォームが存在することを確認するにはどうすればよいですか? Angular 10.2.0 を使用しています
これが違いを生むかどうかはわかりませんが、ページ全体が
<div *ngIf="loaded">
これは、ngOnInit での API 呼び出しの後に設定されます
ngOnInit(): void {
this.dataService.getOpportunity(this.id)
.subscribe(data => {
... //fills the data up
}, error => console.error(error),
() => {
console.log(this.loaded);
console.log(this.ngForm);
});
true (loaded の場合) と undefined (this.ngForm の場合) を出力します。
更新*
データが戻ってきた後にのみフォーム全体がロードされているためです。ページ上にないため、@ViewChild をフックできます。*ngIf をフォーム内の div に配置しましたが、正常に動作しています