programing

이름을 사용하여 컨트롤을 찾을 수 없습니다. 각 반응 형식의 formControlName

codeshow 2023. 8. 5. 11:07
반응형

이름을 사용하여 컨트롤을 찾을 수 없습니다. 각 반응 형식의 formControlName

저는 스택 오버플로에서 많은 질문에서 이 문제를 발견했지만 운이 없었습니다.제가 무엇을 잘못하고 있는지 이해할 수 있도록 도와주세요.

구성 요소:

ngOnInit() {
    this.companyCreatForm = this._formBuilder.group({
      name: [null, [Validators.required, Validators.minLength(5)]],
      about: [null, [Validators.required]],
      businessType: [null, [Validators.required]],
      address: this._formBuilder.group({
        street: [],
        website: [null, [Validators.required]],
        mobile: [null, [Validators.required]],
        email: [null, [Validators.required]],
        pageId: [null, [Validators.required]],
      }),
    });

양식:

<form [formGroup]="companyCreatForm" (ngSubmit)="creat_company()" novalidate class="form-horizontal">
    <div class="panel panel-default" *ngIf="generalPanel">
        <div class="panel-heading">General Info</div>
        <div class="panel-body">
            <div class="form-group">
                <label for="comapny name" class="col-sm-3 control-label">Company's Name</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" placeholder="Company's Name" formControlName="name" #refName>
                    <div *ngIf="companyCreatForm.controls['name'].hasError('required') && refName.touched" class="alert alert-danger">
                        please enter name
                    </div>
                    <div *ngIf="companyCreatForm.controls['name'].hasError('minlength')" class="alert alert-danger">
                        please enter at least 5 characters
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label for="business type" class="col-sm-3 control-label">Business type</label>
                <div class="col-sm-8">
                    <select name="businessType" formControlName="businessType" class="form-control" [(ngModel)]="defaultType">
                        
                        <option  *ngFor="let type of businessTypes" [value]="type.id">{{type.name}}</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="about" class="col-sm-3 control-label">Add Company Description</label>
                <div class="col-sm-8">
                    ​<textarea formControlName="about" class="form-control" id="txtArea" rows="6" cols="70"></textarea>
                </div>
            </div>
        </div>
    </div>

    <div class="panel panel-default">
        <div class="panel-heading">Contact Info</div>
        <div class="panel-body">
            <div class="form-group">
                <label for="address" class="col-sm-3 control-label">Business Address</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
                </div>
            </div>

            <div class="form-group">
                <label for="website" class="col-sm-3 control-label">Website</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="website" placeholder="website">
                </div>
            </div>

            <div class="form-group">
                <label for="telephone" class="col-sm-3 control-label">Telephone</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
                </div>
            </div>

            <div class="form-group">
                <label for="email" class="col-sm-3 control-label">Email</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="email" placeholder="email">
                </div>
            </div>

            <div class="form-group">
                <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
                </div>
            </div>

            <div class="form-group">
                <label for="about" class="col-sm-3  control-label"></label>
                <div class="col-sm-3">
                    ​
                    <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
                </div>
                <label for="about" class="col-sm-2  control-label"></label>
                <div class="col-sm-3">
                    ​<button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
                </div>
            </div>
        </div>
    </div>
</form>

모든 것이 정상이어야 하지만 페이지를 로드할 때 오류를 찾습니다.

이름이 '웹 사이트', '스트리트', '모바일', '이메일', 'pageId'인 컨트롤을 찾을 수 없습니다.

브라우저 콘솔의 전체 오류 페이지는 다음과 같습니다.

CompanyCreateComponent.html:69 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 69, nodeDef: Object, elDef: Object, elView: Object}
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:69
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1149
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.setHasMicrotask @ core.es5.js:4177
onHasTask @ core.es5.js:4140
ZoneDelegate.hasTask @ zone.js:434
ZoneDelegate._updateTaskCount @ zone.js:454
Zone._updateTaskCount @ zone.js:278
Zone.runTask @ zone.js:198
drainMicroTaskQueue @ zone.js:574
ZoneTask.invoke @ zone.js:480
CompanyCreateComponent.html:76 ERROR Error: Cannot find control with name: 'mobile'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:76
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1144
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvoke @ core.es5.js:4131
ZoneDelegate.invoke @ zone.js:380
Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:640
api.microtaskDrainDone @ zone.js:649
drainMicroTaskQueue @ zone.js:582
ZoneTask.invoke @ zone.js:480
CompanyCreateComponent.html:76 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 85, nodeDef: Object, elDef: Object, elView: Object}
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:76
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1149
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvoke @ core.es5.js:4131
ZoneDelegate.invoke @ zone.js:380
Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:640
api.microtaskDrainDone @ zone.js:649
drainMicroTaskQueue @ zone.js:582
ZoneTask.invoke @ zone.js:480
core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: Cannot find control with name: 'street'
Error: Cannot find control with name: 'street'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
    at resolvePromise (zone.js:757)
    at resolvePromise (zone.js:728)
    at zone.js:805
    at ZoneDelegate.invokeTask (zone.js:414)
    at Object.onInvokeTask (core.es5.js:4119)
    at ZoneDelegate.invokeTask (zone.js:413)
    at Zone.runTask (zone.js:181)
    at drainMicroTaskQueue (zone.js:574)
    at HTMLButtonElement.ZoneTask.invoke (zone.js:480)
defaultErrorLogger @ core.es5.js:1084
ErrorHandler.handleError @ core.es5.js:1144
next @ core.es5.js:4757
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.triggerError @ core.es5.js:4188
onHandleError @ core.es5.js:4149
ZoneDelegate.handleError @ zone.js:385
Zone.runGuarded @ zone.js:157
_loop_1 @ zone.js:640
api.microtaskDrainDone @ zone.js:649
drainMicroTaskQueue @ zone.js:582
ZoneTask.invoke @ zone.js:480
CompanyCreateComponent.html:83 ERROR Error: Cannot find control with name: 'email'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:83
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1144
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvokeTask @ core.es5.js:4122
ZoneDelegate.invokeTask @ zone.js:413
Zone.runTask @ zone.js:181
ZoneTask.invoke @ zone.js:476
CompanyCreateComponent.html:83 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 101, nodeDef: Object, elDef: Object, elView: Object}
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:83
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1149
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvokeTask @ core.es5.js:4122
ZoneDelegate.invokeTask @ zone.js:413
Zone.runTask @ zone.js:181
ZoneTask.invoke @ zone.js:476
CompanyCreateComponent.html:90 ERROR Error: Cannot find control with name: 'pageId'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)

지정해야 합니다.formGroupName중첩 컨트롤의 경우

<div class="panel panel-default" formGroupName="address"> <== add this
    <div class="panel-heading">Contact Info</div>

플런커 예제

HTML 코드에서

<form [formGroup]="userForm">
    <input type="text" class="form-control"  [value]="item.UserFirstName" formControlName="UserFirstName">
    <input type="text" class="form-control"  [value]="item.UserLastName" formControlName="UserLastName">
</form>

유형 스크립트 코드

export class UserprofileComponent implements OnInit {
    userForm: FormGroup;
    constructor(){ 
       this.userForm = new FormGroup({
          UserFirstName: new FormControl(),
          UserLastName: new FormControl()
       });
    }
}

이것은 완벽하게 작동하며 오류가 발생하지 않습니다.

그룹 중첩 컨트롤이 없습니다.formGroupName지시의

    <div class="panel-body" formGroupName="address">
      <div class="form-group">
        <label for="address" class="col-sm-3 control-label">Business Address</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
        </div>
      </div>
      <div class="form-group">
        <label for="website" class="col-sm-3 control-label">Website</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="website" placeholder="website">
        </div>
      </div>
      <div class="form-group">
        <label for="telephone" class="col-sm-3 control-label">Telephone</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
        </div>
      </div>
      <div class="form-group">
        <label for="email" class="col-sm-3 control-label">Email</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="email" placeholder="email">
        </div>
      </div>
      <div class="form-group">
        <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
        </div>
      </div>
      <div class="form-group">
        <label for="about" class="col-sm-3  control-label"></label>
        <div class="col-sm-3">
          <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
        </div>
        <label for="about" class="col-sm-2  control-label"></label>
        <div class="col-sm-3">
          <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
        </div>
      </div>
    </div>

저는 당신과 같은 오류를 얻었고 다음과 같이 ts 파일의 제어 이름을 폼 작성기에 선언함으로써 해결했습니다.

 this.myForm = this.formBuilder.group({
        id: [],
        pageName: ['', [Validators.required]],
        urlPage: ['', [Validators.required]],
        title: ['', [Validators.required]],
        description: ['', [Validators.required]],
        pageContent: ['', [Validators.required]],

저도 이 오류가 있었는데, 당신이 해결을 도와줬습니다.formGroup 또는 formGroupName이 올바른 대소문자로 작성되지 않은 경우 컨트롤의 이름을 찾을 수 없습니다.formGroup 또는 formGroupName의 대소문자를 수정하면 정상입니다.

질문의 양이 개체에 따라 달라지기 때문에 동적으로 양식을 생성하려고 했고 추가할 때 오류가 수정되었습니다.ngDefaultControl나에게mat-form-field.

    <form [formGroup]="questionsForm">
        <ng-container *ngFor="let question of questions">
            <mat-form-field [formControlName]="question.id" ngDefaultControl>
                <mat-label>{{question.questionContent}}</mat-label>
                <textarea matInput rows="3" required></textarea>
            </mat-form-field>
        </ng-container>
        <button mat-raised-button (click)="sendFeedback()">Submit all questions</button>
    </form>

sendFeedback()에서 폼 그룹의 값을 선택하여 동적 폼에서 값을 가져옵니다.

  sendFeedbackAsAgent():void {
    if (this.questionsForm.valid) {
      console.log(this.questionsForm.value)
    }
  }

나에게는 컨트롤 이름의 경우가 달랐습니다.

html에서 그것은 계정이었습니다.ID그리고 그것은 계정이었습니다.Id둘 다 일치하도록 사건을 변경한 것이 제 사건을 해결했습니다.

formGroup을 formControlName과 일치하도록 수정합니다.

문제의 요점은 모든 DB 필드가 AutoMapperProfile과 동일한 필드를 사용하여 명시적으로 매핑되어야 한다는 것입니다.

여기에는 모델 속성과 이름이 같아야 하는 폼 필드도 포함됩니다.양식에서 오는 모든 모델의 항목은 데이터베이스 항목에 있는 항목과 동일한 항목이어야 합니다.

예를 들어, AutoMapper Profile이 모델에 대해 8개의 필드를 나열하는 경우 양식에는 8개의 필드가 있어야 합니다.그런 다음 해당 모델을 8개의 필드와 함께 데이터베이스에 저장합니다.

대부분은 처리해야 합니다...

formControlName="xxx"인 내 formBuilder.group의 컨트롤과 관련된 태그를 사용하여 이 오류를 해결했습니다.

.ts 파일:

        this.reportForm = this.formBuilder.group({
            dateFrom: this.dateFromFC,
            dateTo: this.dateToFC,
            user: this.userFC,
        });

.html 파일:

매트 양식 필드 입력 내부

 <input type="text" matInput formControlName="user" [matAutocomplete]="auto">

나를 위해서라도.[formGroup]" 류가발습니다했오생▁"다▁"▁popping니▁the▁up▁was"로 뜨는 중이었습니다.Cannot find control with name:''".
제가 추가했을 때 고쳐졌습니다.ngModel 값과함께대와 입력 formControlName="fileName"

  <form class="upload-form" [formGroup]="UploadForm">
  <div class="row">
    <div class="form-group col-sm-6">
      <label for="fileName">File Name</label>
      <!-- *** *** *** Adding [(ngModel)]="FileName" fixed the issue-->
      <input type="text" class="form-control" id="fileName" [(ngModel)]="FileName"
        placeholder="Enter file name" formControlName="fileName"> 
    </div>
    <div class="form-group col-sm-6">
      <label for="selectedType">File Type</label>
      <select class="form-control" formControlName="selectedType" id="selectedType" 
        (change)="TypeChanged(selectedType)" name="selectedType" disabled="true">
        <option>Type 1</option>
        <option>Type 2</option>
      </select>
    </div>
  </div>
  <div class="form-group">
    <label for="fileUploader">Select {{selectedType}} file</label>
    <input type="file" class="form-control-file" id="fileUploader" (change)="onFileSelected($event)">
  </div>
  <div class="w-80 text-right mt-3">
    <button class="btn btn-primary mb-2 search-button cancel-button" (click)="cancelUpload()">Cancel</button>
    <button class="btn btn-primary mb-2 search-button" (click)="uploadFrmwrFile()">Upload</button>
  </div>
 </form>

그리고 컨트롤러에서.

ngOnInit() {
this.UploadForm= new FormGroup({
  fileName: new FormControl({value: this.FileName}),
  selectedType: new FormControl({value: this.selectedType, disabled: true}, Validators.required),
  frmwareFile: new FormControl({value: ['']})
});
}

언급URL : https://stackoverflow.com/questions/44431613/cannot-find-control-with-name-formcontrolname-in-angular-reactive-form

반응형