FormBuilder 컨트롤의 수동 값 설정
미치겠네, 난 너무 바빠서 하루 종일 이 일에 매달릴 여유가 없어.
컴포넌트 내에서 제어값('dept')을 수동으로 설정하려고 하는데, 새 값 로그조차 제대로 작동하지 않습니다.
다음은 Form Builder 인스턴스입니다.
initForm() {
this.form = this.fb.group({
'name': ['', Validators.required],
'dept': ['', Validators.required],
'description': ['', Validators.required],
});
}
선택한 Dept를 수신하는 이벤트핸들러입니다
deptSelected(selected: { id: string; text: string }) {
console.log(selected) // Shows proper selection!
// This is how I am trying to set the value
this.form.controls['dept'].value = selected.id;
}
이 , ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」this.form
!!가!!!!!!!!!!!! 다른 사용법을 본 요.updateValue()
하지만 이것은 베타.1이며 컨트롤에 호출하는 유효한 방법은 아닌 것 같습니다.
updateValueAndValidity()
하지 못하고
★★★★★★★★★★★★★★★★.ngControl="dept"
커스텀 디렉티브/컴포넌트로서 폼의 나머지 부분과 마찬가지로 폼 요소에도 적용됩니다.
<ng-select
[data]="dept"
[multiple]="false"
[items]="depts"
(selected)="deptSelected($event)" <!-- This is how the value gets to me -->
[placeholder]="'No Dept Selected'">
</ng-select>
갱신일 : 2017년 3월 19일
this.form.controls['dept'].setValue(selected.id);
구:
지금으로서는, 타입 캐스트를 하지 않을 수 없습니다.
(<Control>this.form.controls['dept']).updateValue(selected.id)
별로 우아하지 않군요.향후 버전에서는 이 기능이 개선되었으면 좋겠습니다.
Angular 2 Final(RC5+)은 API를 사용합니다.patchValue()
API 메서드는 일부 필드만 지정하면 되는 부분 양식 업데이트를 지원합니다.
this.form.patchValue({id: selected.id})
,도 있어요.setValue()
모든 양식 필드를 포함하는 개체가 필요한 API 메서드입니다.누락된 필드가 있으면 오류가 발생합니다.
양식 제어를 사용하는 경우 가장 간단한 방법은 다음과 같습니다.
this.FormName.get('ControlName').setValue(value);
Aangular 2 final은 API를 업데이트했습니다.그들은 이를 위해 많은 방법을 추가했다.
컨트롤러에서 폼 제어를 갱신하려면 다음 절차를 수행합니다.
this.form.controls['dept'].setValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
에러를 리셋 할 필요는 없습니다.
레퍼런스
https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html
https://toddmotto.com/angular-2-form-controls-patch-value-set-value
다음 방법을 사용하여 반응형 양식 컨트롤의 값을 업데이트할 수 있습니다.당신의 필요에 따라 다음 방법 중 하나가 적합합니다.
setValue()를 사용하는 메서드
this.form.get("dept").setValue(selected.id);
this.form.controls["dept"].setValue(selected.id);
patch Value()를 사용하는 메서드
this.form.get("dept").patchValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
this.form.patchValue({"dept": selected.id});
마지막 방법은 폼의 모든 컨트롤을 루프하므로 단일 컨트롤을 업데이트할 때 권장되지 않습니다.
이벤트 핸들러 내에서 임의의 방법을 사용할 수 있습니다.
deptSelected(selected: { id: string; text: string }) {
// any of the above method can be added here
}
필요에 따라 를 사용하여 폼 그룹의 여러 컨트롤을 업데이트할 수 있습니다.
this.form.patchValue({"dept": selected.id, "description":"description value"});
이미 답변이 있는 것은 알지만, 다른 신규 가입자가 명확한 아이디어를 얻을 수 있도록 폼의 가치를 어떻게 갱신해야 하는지 간략하게 답변하고 싶습니다.
당신의 폼 구조는 그것을 예로 들기에 매우 완벽합니다. 그래서, 제 답변 내내, 저는 그것을 폼으로 나타낼 것입니다.
this.form = this.fb.group({
'name': ['', Validators.required],
'dept': ['', Validators.required],
'description': ['', Validators.required]
});
따라서 폼은 3개의 FormControl을 가진 Form Group 유형의 객체입니다.
모델 값을 업데이트하는 방법은 두 가지가 있습니다.
개별 컨트롤의 새 값을 설정하려면 setValue() 메서드를 사용합니다.setValue() 메서드는 폼 그룹의 구조를 엄격하게 준수하며 컨트롤 값 전체를 대체합니다.
patchValue() 메서드를 사용하여 폼모델에서 변경된 오브젝트에 정의된 속성을 바꿉니다.
setValue() 메서드의 엄격한 체크는 복잡한 형식의 네스트 오류를 포착하는 데 도움이 되지만 이러한 오류에 대해서는 patchValue()가 자동으로 실패합니다.
Angular 공식 설명서 여기서
따라서 여러 컨트롤이 포함된 폼 그룹 인스턴스 값을 업데이트할 때 모델의 일부만 업데이트할 수 있습니다.찾고 있는 것은 patch Value()입니다.
예를 들어 보겠습니다.patchValue()를 사용하는 경우
this.form.patchValue({
dept: 1
});
//here we are just updating only dept field and it will work.
그러나 setValue()를 사용하는 경우 폼 그룹의 구조를 엄격하게 준수하기 때문에 풀 모델을 업데이트해야 합니다.
this.form.setValue({
dept: 1
});
// it will throw error.
폼 그룹 모델의 모든 속성을 전달해야 합니다.이것처럼.
this.form.setValue({
name: 'Mr. Bean'
dept: 1,
description: 'spome description'
});
이런 스타일은 잘 안 써요.코드를 보다 깨끗하고 알기 쉽게 유지하기 위해 다음과 같은 방법을 사용하는 것이 좋습니다.
모든 컨트롤을 개별 변수로 선언하고 setValue()를 사용하여 특정 컨트롤을 업데이트합니다.
위의 양식에 대해서는 이렇게 하겠습니다.
get companyIdentifier(): FormControl {
return this.form.get('name') as FormControl;
}
get dept(): FormControl {
return this.form.get('dept') as FormControl;
}
get description(): FormControl {
return this.form.get('description') as FormControl;
}
양식 컨트롤을 업데이트해야 할 경우 해당 속성을 사용하여 업데이트하십시오.이 예에서는 사용자가 드롭다운목록에서 항목을 선택할 때 질문자가 부서 양식 컨트롤을 업데이트하려고 했습니다.
deptSelected(selected: { id: string; text: string }) {
console.log(selected) // Shows proper selection!
// instead of using this.form.controls['dept'].setValue(selected.id), I prefer the following.
this.dept.setValue(selected.id); // this.dept is the property that returns the 'dept' FormControl of the form.
}
FormGroup의 모든 속성 및 메서드를 알기 위해 FormGroup API를 찾아보는 것이 좋습니다.
추가: getter에 대한 자세한 내용은 여기를 참조하십시오.
다음과 같이 시도해 볼 수 있습니다.
deptSelected(selected: { id: string; text: string }) {
console.log(selected) // Shows proper selection!
// This is how I am trying to set the value
this.form.controls['dept'].updateValue(selected.id);
}
JS Doc의 두.updateValue
방법 : https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/model.ts#L269
난 하나도 안 먹혔어나는 해야만 했다:
this.myForm.get('myVal').setValue(val);
let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);
this.form.complexForm.patchValue(cloneObj);
각 필드를 수동으로 설정하지 않을 경우.
@Filoche의 Angular 2의 업데이트된 솔루션.사용법
(<Control>this.form.controls['dept']).updateValue(selected.id)
import { FormControl } from '@angular/forms';
(<FormControl>this.form.controls['dept']).setValue(selected.id));
또는 @Angular University의 솔루션을 사용하여patchValue
힌트: 를 사용하고 있는 경우setValue
폼에 모든 속성을 제공하지 않으면 오류가 발생합니다.
Must supply a value for form control with name: 'stateOrProvince'.
그래서 당신은 아마 그것을 사용하고 싶을 것이다.patchValue
그러나 전체 양식을 업데이트하려고 하면 위험할 수 있습니다.나는 가지고 있다.address
없을지도 모른다stateOrProvince
또는stateCd
미국인지 전 세계인지에 따라 다릅니다.
대신 다음과 같이 업데이트할 수 있습니다. 그러면 null이 기본값으로 사용됩니다.
this.form.setValue( { stateOrProvince: null, stateCd: null, ...address } );
언급URL : https://stackoverflow.com/questions/35039610/manually-set-value-for-formbuilder-control
'source' 카테고리의 다른 글
Bash 스크립트에서 중복 항목 제거 (0) | 2023.04.24 |
---|---|
ARC와 호환되는 Objective-C 싱글톤을 구현하려면 어떻게 해야 하나요? (0) | 2023.04.24 |
왼쪽 조인 포함 상위 1위 (0) | 2023.04.19 |
행 및 열 인덱스로 WPF 그리드의 제어에 프로그래밍 방식으로 액세스하는 방법은 무엇입니까? (0) | 2023.04.19 |
커밋 메시지로 Git 저장소를 검색하는 방법 (0) | 2023.04.19 |