Angular 2에서 제출 한 후 양식을 지우는 방법은 무엇입니까?


88

템플릿이있는 간단한 각도 2 구성 요소가 있습니다. 제출 후 양식 및 모든 필드를 지우는 방법은 무엇입니까? 페이지를 새로 고침 할 수 없습니다. date.setValue('')필드 와 함께 설정된 데이터 는 stil touched입니다.

import {Component} from 'angular2/core';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators, Control} from 'angular2/common';

@Component({
    selector: 'loading-form',
    templateUrl: 'app/loadings/loading-form.component.html',
    directives: [FORM_DIRECTIVES]
})

export class LoadingFormComponent {
    private form:ControlGroup;
    private date:Control;
    private capacity:Control;

    constructor(private _loadingsService:LoadingsService, fb:FormBuilder) {
        this.date = new Control('', Validators.required);
        this.capacity = new Control('', Validators.required);
        this.form = fb.group({
            'date': this.date,
            'capacity': this.capacity
        });
    }

    onSubmit(value:any):void {
        //send some data to backend
    }
}

loading-form.component.html

<div class="card card-block">
    <h3 class="card-title">Loading form</h3>

    <form (ngSubmit)="onSubmit(form.value)" [ngFormModel]="form">
        <fieldset class="form-group" [class.has-danger]="!date.valid && date.touched">
            <label class="form-control-label" for="dateInput">Date</label>
            <input type="text" class="form-control form-control-danger form-control-success" id="dateInput"
                   min="0" placeholder="Enter loading date"
                   [ngFormControl]="form.controls['date']">
        </fieldset>
        <fieldset class="form-group" [class.has-danger]="!capacity.valid && capacity.touched">
            <label class="form-control-label" for="capacityInput">Capacity</label>
            <input type="number" class="form-control form-control-danger form-control-success" id="capacityInput"
                   placeholder="Enter capacity"
                   [ngFormControl]="form.controls['capacity']">
        </fieldset>
        <button type="submit" class="btn btn-primary" [disabled]="!form.valid">Submit
        </button>
    </form>
</div>

답변:


138

https://angular.io/docs/ts/latest/guide/reactive-forms.html ( "양식 플래그 재설정"섹션) 도 참조 하십시오.

> = RC.6

RC.6에서는 양식 모델 업데이트가 지원되어야합니다. 새 양식 그룹 생성 및 할당myForm

[formGroup]="myForm"

또한 지원됩니다 ( https://github.com/angular/angular/pull/11051#issuecomment-243483654 )

> = RC.5

form.reset();

새 양식 모듈 (> = RC.5) NgForm에는 reset()메소드가 있으며 양식 reset이벤트 도 지원합니다 . https://github.com/angular/angular/blob/6fd5bc075d70879c487c0188f6cd5b148e72a4dd/modules/%40angular/forms/src/directives/ng_form.ts#L179

<= RC.3

이것은 작동합니다.

onSubmit(value:any):void {
  //send some data to backend
  for(var name in form.controls) {
    (<Control>form.controls[name]).updateValue('');
    /*(<FormControl>form.controls[name]).updateValue('');*/ this should work in RC4 if `Control` is not working, working same in my case
    form.controls[name].setErrors(null);
  }
}

또한보십시오


2
@ masel.popowo 예, 원하는 pristine경우 ..., 양식을 다시 작성하는 것이 현재 유일한 옵션입니다.
— Günter Zöchbauer

@ günter-zöchbauer 양식을 어떻게 다시 작성합니까?
— SimonHawesome

2
아직 직접 시도하지는 않았지만 제어 그룹을 삭제하고 새 그룹을 만드는 것 같습니다. 필요한 경우 반복적으로 호출 할 수 있도록 코드를 함수로 이동합니다.
— Günter Zöchbauer

setErrors ()에 +1. 그건 그렇고, 실수는 다른 사람이 비슷한 경우에 내가 만든 실수를 문서화합니다. 예를 들어 자리 표시자를 사용하는 경우 'foo'는 control.updateValue ( 'foo')를 호출하지 않고 대신 control.setValue (null)을 호출합니다.
— 마이크 Argyriou

나는 setValue()통제 에 대한 방법에 대해 모른다 . 만 updateValue() github.com/angular/angular/blob/master/modules/angular2/src/...
— 귄터 Zöchbauer

34

Angular2 RC5 myFormGroup.reset()에서 트릭을 수행하는 것 같습니다.


이것은 각도 4에서 작동하며 양식 유효성 검사를 재설정하는 데 사용되었습니다
— Grim

13

제출 후 양식을 재설정하려면을 호출하기 만하면 this.form.reset()됩니다. reset()그것을 호출 하면 :

  1. 컨트롤과 자식 컨트롤을 원래 대로 표시합니다 .
  2. 컨트롤 및 자식 컨트롤을 변경되지 않은 것으로 표시 합니다.
  3. 컨트롤 및 자식 컨트롤의 값 을 사용자 지정 값 또는 null로 설정 합니다.
  4. 영향을받는 당사자의 가치 / 유효성 / 오류 를 업데이트 합니다 .

자세한 답변을 보려면이 풀 리퀘스트 를 찾으십시오 . 참고로이 PR은 이미 2.0.0으로 병합되었습니다.

이 정보가 도움이되기를 바라며 Angular2 Forms와 관련하여 다른 질문이 있으면 알려주세요.


1
재설정을 사용하면 유효성 검사가 적용되지 않습니다. 둘 다 작동하도록하려면 어떻게해야합니까?
— Nisha

11

전화하다 clearForm();.ts 파일에서

양식 데이터를 지우려면 아래 예제 코드 조각과 같이 시도하십시오.

clearForm() {

this.addContactForm.reset({
      'first_name': '',
      'last_name': '',
      'mobile': '',
      'address': '',
      'city': '',
      'state': '',
      'country': '',
       'zip': ''
     });
}

9
import {Component} from '@angular/core';
import {NgForm} from '@angular/forms';
@Component({
    selector: 'example-app',
    template: '<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
        <input name="first" ngModel required #first="ngModel">
        <input name="last" ngModel>
        <button>Submit</button>
    </form>
    <p>First name value: {{ first.value }}</p>
    <p>First name valid: {{ first.valid }}</p>
    <p>Form value: {{ f.value | json }}</p>
    <p>Form valid: {{ f.valid }}</p>',
})
export class SimpleFormComp {
    onSubmit(f: NgForm) {

        // some stuff

        f.resetForm();
    }
}

@ 모든 필드를 지워야 할 때 제대로 작동합니다. 그러나 특정 필드 만 지우려면 어떻게 구현할 수 있습니까?
— Akhilesh Pothuri

9

Angular 7.3에서 수행하는 방법은 다음과 같습니다.

// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {

    form.reset();

    Object.keys(form.controls).forEach(key => {
      form.get(key).setErrors(null) ;
    });
}

전화 할 필요가 없었습니다 form.clearValidators()


2
이것이 유효성 검사기가있는 컨트롤이있는 FormBuilder로 빌드 된 양식을 지우는 가장 좋은 (그리고 저에게만 효과가있는) 솔루션입니다.
— mmied

8

방법은 다음과 같습니다. Angular 8 :

양식의 로컬 참조를 가져옵니다.

<form name="myForm" #myForm="ngForm"></form>
@ViewChild('myForm', {static: false}) myForm: NgForm;

그리고 양식을 재설정해야 할 때마다 resetForm메소드를 호출하십시오 .

this.myForm.resetForm();

작동 하려면 FormsModulefrom 이 필요 @angular/forms합니다. 모듈 가져 오기에 추가해야합니다.


1
@ViewChildAngular 8에서는 2 개의 인수가 필요합니다. @ViewChild('myForm', {static: false}) myForm: NgForm;
— Tanzeel

6

각도 버전 4에 다음을 사용할 수 있습니다.

this.heroForm.reset();

그러나 다음과 같은 초기 값이 필요할 수 있습니다.

ngOnChanges() {
 this.heroForm.reset({
  name: this.hero.name, //Or '' to empty initial value. 
  address: this.hero.addresses[0] || new Address()
 });
}

개체 참조에서 null 문제를 해결하는 것이 중요합니다.

참조 링크 , "양식 플래그 재설정"을 검색하십시오.


고마워요. 이것이 내가 원하는거야.
— Dhaval Mistry


1

다른 해결책을 찾았습니다. 약간 엉망이지만 angular2 세계에서 널리 사용 가능합니다.

* ngIf 지시문은 양식을 제거하고 다시 작성하므로 간단히 * ngIf를 양식에 추가하고 일종의 formSuccessfullySent변수에 바인딩 할 수 있습니다 . => 이것은 양식을 다시 생성하므로 입력 제어 상태를 재설정합니다.

물론 모델 변수도 지워야합니다. 양식 필드에 대한 특정 모델 클래스를 갖는 것이 편리하다는 것을 알았습니다. 이렇게하면이 모델 클래스의 새 인스턴스를 만드는 것처럼 간단하게 모든 필드를 재설정 할 수 있습니다. :)


추가 : 저는 아직 그러한 재설정 방법이없는 AngularDart를 사용하고 있습니다. 아니면 적어도 지금은 발견하지 못했습니다. : D
— Benjamin Jesuiter

RC.6에서는 양식 모델을 다시 초기화하기 만하면됩니다. 양식 모델 작성을 메소드로 이동하는 경우이 메소드를 호출하면 양식이 재설정됩니다.
— Günter Zöchbauer

@ GunterZöchbauer 오 대박! Angular2 for Dart에서도이 기능을 사용하기를 기다릴 수 없습니다! :) 내 접근 방식이 문제이기 때문에 : 내 양식에 모든 입력 요소 목록이 있습니다. 나는 dart-native querySelectorAll를 통해 ngAfterViewInit. 이 목록을 사용하여 양식을 제출하는 대신 keydown.enter의 다음 입력 요소에 초점을 맞 춥니 다. 이 목록은 ngIf를 사용하여 양식을 다시 초기화 할 때 중단됩니다. :(
— Benjamin Jesuiter

네, 문제를 해결했습니다. 양식 모델을 재설정 할 때 InputElement 인스턴스를 다시 쿼리 할 수 ​​있습니다.
— Benjamin Jesuiter

0

흠, 이제 (2017 년 1 월 23 일 각도 2.4.3으로) 다음과 같이 작동하도록 만들었습니다.

newHero() {
    return this.model = new Hero(42, 'APPLIED VALUE', '');
}
<button type="button" class="btn btn-default" (click)="heroForm.resetForm(newHero())">New Hero</button>

0

아래 코드는 Angular 4에서 나를 위해 작동합니다.

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class RegisterComponent implements OnInit {
 registerForm: FormGroup; 

 constructor(private formBuilder: FormBuilder) { }   

 ngOnInit() {
    this.registerForm = this.formBuilder.group({
      empname: [''],
      empemail: ['']
    });
 }

 onRegister(){
    //sending data to server using http request
    this.registerForm.reset()
 }

}

0

this.myForm.reset ();

이것으로 충분합니다 ... 원하는 출력을 얻을 수 있습니다


1
이 코드 줄이 문제를 해결하는 방법에 대한 설명을 추가하십시오.
— Sfili_81

0

제출시 완전한 양식을 재설정하려면 Angular에서 reset ()을 사용할 수 있습니다. 아래 예제는 Angular 8에서 구현되었습니다. 아래는 이메일을 입력으로받는 구독 양식입니다.

<form class="form" id="subscribe-form" data-response-message-animation="slide-in-left" #subscribeForm="ngForm"
(ngSubmit)="subscribe(subscribeForm.value); subscribeForm.reset()">
<div class="input-group">
   <input type="email" name="email" id="sub_email" class="form-control rounded-circle-left"
      placeholder="Enter your email" required ngModel #email="ngModel" email>
   <div class="input-group-append">
      <button class="btn btn-rounded btn-dark" type="submit" id="register"
         [disabled]="!subscribeForm.valid">Register</button>
   </div>
</div>
</form>

공식 문서 참조 : https://angular.io/guide/forms#show-and-hide-validation-error-messages .


-3
resetForm(){
    ObjectName = {};
}

이 코드가 질문에 답할 수 있지만 문제를 해결하는 이유 / 방법을 설명하는 설명을 추가해야합니다.
— BDL

'touched', 'pristine'등 ... 클래스를 원래 값으로 되 돌리지 않습니다.
— Pac0

@Shivendra 이것은 특히 문제에 대해 작동하지만 일반적이지 않습니다. 당신은 당신이 만들고있어 object빈 아니라 form.
— Tanzeel
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.