我正在尝试在HTML中显示表单控件“名称”
表单控件“名称”分组在表单组“样本”内
我不了解等级
这是HTML代码:
<p contenteditable="true" [formControl]="name"> </p>
<div>
FORM GROUP Value : {{ sample.value | json }}
<br>
FORM CONTROL VALUE : {{sample.value.name}}
</div>
这里是TYPESCRIPT CODE:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
@Component({
selector: 'app-ng-contenteditable-my-example1',
templateUrl: './ng-contenteditable-my-example1.component.html',
styleUrls: ['./ng-contenteditable-my-example1.component.scss']
})
export class NgContenteditableMyExample1Component implements OnInit {
constructor(private formbuilder: FormBuilder,
private titleService: Title,
private _router: Router) {
this.titleService.setTitle('formbuilder');
}
ngOnInit() {
// console.log("Sample Status : " + this.sample.status);
this.sample.controls.name.setValue(`Ashish`)
}
sample : FormGroup = new FormGroup({
name : new FormControl(null,[Validators.nullValidator])
});
}
我遇到此错误:
NgContenteditableMyExample1Component.ngfactory.js? [sm]:1 ERROR Error: Cannot find control with unspecified name attribute
at _throwError (forms.js:3357)
at setUpControl (forms.js:3181)
at FormControlDirective.ngOnChanges (forms.js:7102)
at checkAndUpdateDirectiveInline (core.js:31906)
at checkAndUpdateNodeInline (core.js:44367)
at checkAndUpdateNode (core.js:44306)
at debugCheckAndUpdateNode (core.js:45328)
at debugCheckDirectivesFn (core.js:45271)
at Object.eval [as updateDirectives] (NgContenteditableMyExample1Component.html:23)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:45259)
答案 0 :(得分:0)
这是因为[formControl]="name"
是一个data-bound属性,这意味着它将在您的查找变量变量中组件类。因为没有任何东西,所以会得到该错误。
您可以通过执行name
或formControlName='name'
此外,请注意,[formControlName]="'name'"
指令必须引用FormControl实例,而不是映射到formControl
的 string 。
答案 1 :(得分:0)
您可以通过以下方式访问在 FormGroup 中定义的 FormControl:
<p contenteditable="true" [formControl]="sample.get('name')"> </p>