4 formControl
초와 하나의 입력 필드 만 있는 각도 2 반응 형이 있습니다. 내가 원하는 것은 사용자에게 정보를 하나씩 채워달라고 요청하는 것입니다. 그래서, 나는 할당있어 firstControlName
속성 호출 currentFormControlName
에 ngOnInit
와 템플릿 파일 입력 필드와 바인딩. 사용자가 이름을 입력하면 필드가 유효하며 제출시 currentFormControlName
속성을 다음 formControlName으로 변경합니다 . 그러나 문제는 바인딩이 업데이트되지 않는다는 것입니다. 입력 필드는 여전히에 결합되어 name
있습니다. 입력 필드에 무언가를 입력하면의 값 name
이 업데이트되지 않습니다 email
.
app.component.ts
ngOnInit() {
this.form = this.builder.group({
'name': ['', Validator.required],
'email': ['', Validator.email],
'phone': ['', Validator.required],
'password': ['', Validator.required],
});
this.currentFormControlName = 'name';
}
submit() {
this.currentFormControlName = 'email'; // Setting it manually just for the demo of this question.
}
app.component.html
<form [formGroup]="form">
<input type="text" [formControlName]="currentFormControlName">
<input type="submit" (click)="submit()">
</form>
최신 정보
FormControlDirective
컨트롤을 전환 하는 데 사용할 수도 있습니다.
[formControl]="form.get(currentFormControlName)"
이전 답변
다음이 있다고 가정 해 봅시다.
template.html
<form [formGroup]="form" #formDir="ngForm">
<input type="text" #controlDir [formControlName]="currentFormControlName">
<input type="submit" (click)="submit()">
</form>
<pre>{{ form.value | json }}</pre>
제출 버튼을 클릭하면 다음 currentFormControlName
과 같은 새 이름으로 컨트롤을 변경 하고 등록 할 수 있습니다.
component.ts
form: FormGroup;
@ViewChild('formDir') formDir: FormGroupDirective;
@ViewChild('controlDir', { read: FormControlName }) controlDir: FormControlName;
currentFormControlName: string;
constructor(private builder: FormBuilder) {}
ngOnInit() {
this.form = this.builder.group({
'name': ['', Validators.required],
'email': ['', Validators.email],
'phone': ['', Validators.required],
'password': ['', Validators.required],
});
this.currentFormControlName = 'name';
}
submit() {
this.formDir.removeControl(this.controlDir);
this.controlDir.name = this.currentFormControlName = 'email'
this.formDir.addControl(this.controlDir);
}
그 후 입력 요소가 email
가치 를 관리 합니다. 그래서 우리가 뭔가를 입력하면 가치에 input
반영됩니다form.email
이 솔루션은 FormControlName 소스 코드를 기반으로 합니다.
ngOnChanges(changes: SimpleChanges) {
if (!this._added) this._setUpControl();
if (isPropertyUpdated(changes, this.viewModel)) {
this.viewModel = this.model;
this.formDirective.updateModel(this, this.model);
}
}
이 지시문이 한 번만 제어하는 것을 볼 수 있습니다. 그러나 다음과 같은 ngOnDestroy 후크도 있습니다.
ngOnDestroy(): void {
if (this.formDirective) {
this.formDirective.removeControl(this);
}
}
나에게 몇 가지 아이디어를 주었다
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다