问题描述
无法解决无法绑定到 formGroup 因为它不是表单的已知属性.
Unable to solve Can't bind to formGroup since it isn't a known property of form.
我已经尝试了所有的解决方案已经添加 ReactiveFormsModule , FormsModule
也试过 [formGroup]
和 [FormGroup]
仍然得到同样的错误
I have already tried all the solutionsalready add ReactiveFormsModule , FormsModule
also tried [formGroup]
and [FormGroup]
still getting the same error
import { ReactiveFormsModule , FormsModule } from '@angular/forms';
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
]
我的表格
<form [formGroup]="addPostForm" (ngSubmit)="addNewPost()">
<ion-item>
<ion-label class="grey" position="stacked">Caption </ion-label>
<ion-input type="text" formControlName="caption"></ion-input>
</ion-item>
<ion-button expand="block" type="submit" shape="round">Save</ion-button>
</form>
add-post.page.ts
add-post.page.ts
import { Component, OnInit } from '@angular/core';
import { IonSlides } from '@ionic/angular';
import { ApiService } from '../services/api.service';
import { Router } from "@angular/router"
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms';
@Component({
selector: 'app-add-post',
templateUrl: './add-post.page.html',
styleUrls: ['./add-post.page.scss'],
})
export class AddPostPage implements OnInit {
addPostForm: FormGroup;
picture = null;
submitted = false;
success = false;
constructor(
private api: ApiService,
private FormBuilder: FormBuilder,
private router: Router,
) {
this.addPostForm = this.FormBuilder.group({
caption: ['']
});
}
推荐答案
您需要在 app.component.ts 文件中设置表单.相同的请参考下面的代码,
You need to setup form in app.component.ts file. Please refer below code for the same,
import { Component } from '@angular/core';
import { AuthenticationService } from './services/authentication.service';
import { Router } from '@angular/router';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
navigate : any;
//Need to define addPostForm here.
addPostForm = new FormGroup({
caption: new FormControl('')
});
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private authenticationService: AuthenticationService,
private router: Router
) {
this.sideMenu();
this.initializeApp();
}
有关更多参考,请参阅 this 反应式表单的 angular 文档.
For more reference please refer this angular docs for reactive forms.
注意:如果你的组件是在另一个模块中导入的,那么你需要在这个模块中导入ReactiveFormsModule.
Note: If your component is imported in another module then in other module you need to import ReactiveFormsModule in this module.
这篇关于无法绑定到“formGroup",因为它不是 Angular 8 中“form"的已知属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!