在我的项目中,我有两个标签ReactiveForms
,其中表单的内容是嵌套组件。我已根据此stackoverflow答案Angular 2 - form group component尝试修复错误Error: formGroup expects a FormGroup instance. Please pass one in.
,但我仍然收到原始错误。任何想法如何解决它?
app.component.ts(Parent)
import {Component, ViewChild, OnInit} from '@angular/core';
import {bootstrap} from '@angular/platform-browser-dynamic';
import {TabContent} from './tab-content.component';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'material-app',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
private inputData;
private formGroup1;
private formGroup2;
@ViewChild(TabContent) content: TabContent;
constructor() {
}
ngOnInit() {
this.formGroup1 = new FormGroup({
inputControler: new FormControl()
});
this.formGroup2 = new FormGroup({
inputControler: new FormControl()
});
}
getData() {
this.inputData = this.content.state.nativeElement.value;
//console.log(this.content.state);
}
}
app.component.html
<md-tab-group>
<md-tab label="One">
<form [formGroup]="formGroup1">
<tab-content [group]="formGroup1"></tab-content>
</form>
</md-tab>
<md-tab label="Two">
<form [formGroup]="formGroup2">
<tab-content [group]="formGroup2"></tab-content>
</form>
</md-tab>
</md-tab-group>
<button md-raised-button color="primary" (click)="getData()">GET DATA</button>
<p>Data: {{ inputData }}</p>
tab-content.component.ts(儿童)
import {Component, ViewChild, Input} from '@angular/core';
import {bootstrap} from '@angular/platform-browser-dynamic';
@Component({
selector: 'tab-content',
template: `
<md-input-container width="100%" [formGroup]="group">
<input #state mdInput placeholder="State" formControlName="inputControler">
</md-input-container>
`
})
export class TabContent {
@ViewChild('state') state;
@Input() group;
constructor() {
}
}