angular - 错误 : formControlName must be used with a parent formGroup directive. 您需要添加一个 formGroup 指令 - Angular react 形式

标签 angular angular2-forms

我有以下模板。我正在尝试掌握响应式表单,但遇到了问题。

<form [formGroup]="guestForm" novalidate>
    <div class="panel-body">
        <form>
            <div class="col-md-12 col-sm-12">
                <div class="form-group col-md-3 col-sm-6">
                    <label>First Name*  </label>
                    <input formControlName="firstname" type="text" class="form-control input-sm">
                </div>
            </div>
        </form>
    </div>
</form>

然后在我的组件中我有:

@Component({
    selector: 'guest-input',
    templateUrl: './guest-input.component.html',
})
export class GuestInputComponent implements OnInit {
    @Input()
    guest: Guest;

    guestForm: FormGroup;
    
    constructor(private _fb: FormBuilder) { }

    ngOnInit() {
        this.guestForm = this._fb.group({
            firstname: ['test', [Validators.required, Validators.minLength(3)]]
        });
    }
}

这一切对我来说都很好,但出于某种原因我得到:

Error: Uncaught (in promise): Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).

我以为我已经在我的 <form> 中声明了这一点.

最佳答案

你在带有 FormGroup 指令的 form 标签内嵌套了 form 标签,将其移除:

<form [formGroup]="guestForm" novalidate>
    <div class="panel-body">
        <form> -> Remove this
            <div class="col-md-12 col-sm-12">
                <div class="form-group col-md-3 col-sm-6">
                    <label>First Name*  </label>
                    <input formControlName="firstname" type="text" class="form-control input-sm">
                </div>
            </div>
        </form> -> Remove this
    </div>
</form>

关于angular - 错误 : formControlName must be used with a parent formGroup directive. 您需要添加一个 formGroup 指令 - Angular react 形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43305975/

相关文章:

Angular 2 自定义验证单元测试

dart - 在angular2中访问数据集映射

angular - 在 Angular 2 模板中使用普通 POST 表单会导致 : "Template parse errors: No provider for ControlContainer"

validation - 导致 "Expression has changed after it was checked"异常的 FormBuilder 控件

Angular:将 XML 转换为 JSON

ios - 无法使用 ionic2/angular2 在 iOS/Safari 中正确显示日期时间

Angular 正式 5.10.3 更改时自定义切换事件

Angular 2/ ionic 2 : databinding

angular - Angular2 网格的 Kendo UI : add row form on bottom instead of top of list

angular - 手动清理字符串