รูปแบบปฏิกิริยาเชิงมุม - จะรีเซ็ตเป็นค่าดั้งเดิมเมื่อผู้ใช้เปลี่ยนกลับ UI เปลี่ยนเป็นค่าดั้งเดิมหรือไม่

Aug 19 2020

ฉันต้องการเปิดใช้งานปุ่มส่งในแบบฟอร์มก็ต่อเมื่อการป้อนข้อมูลแบบฟอร์มมีการเปลี่ยนแปลง

ส่งปุ่มควรจะปิดใช้งานเมื่อค่าการควบคุมรูปแบบจะไม่เปลี่ยนแปลง

ฉันพยายามใช้แฟล็ก FormGroup.pristineสำหรับการเปิด / ปิดการใช้งานปุ่มส่ง

ใช้งานได้ดีสำหรับการเปิดใช้งานปุ่ม

อย่างไรก็ตามจะไม่ได้รับการรีเซ็ตtrueเมื่อค่าใน UI เปลี่ยนกลับเป็นค่าเดิม

รหัสส่วนประกอบ:

import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html',
  styleUrls: ['./registration-form.component.scss']
})
export class RegistrationFormComponent {
  public registrationForm;
  public formValues = {
      gender: 1,
    };

  constructor(private formBuilder: FormBuilder) {
    this.registrationForm = formBuilder.group(this.formValues);
  }

  onSubmit(formData) {
    console.log('Your form is submitted', formData);
    this.registrationForm.reset(this.formValues);
  }
}
<form class="registration-form" [formGroup]="registrationForm" (ngSubmit)="onSubmit(registrationForm.value)">
  <div>
    <label for="gender">Gender</label>
    <select id="gender" formControlName="gender">
      <option value=1>female</option>
      <option value=2>male</option>
      <option value=3>do not specify</option>
    </select>
  </div>
  <input type="submit" [disabled]="registrationForm.pristine">
</form>

โดยค่าเริ่มต้นตัวเลือก "หญิง" จะถูกเลือกในกล่องเลือก

เมื่อผู้ใช้เปลี่ยนเป็น "ชาย" เช่นปุ่มส่งจะเปิดใช้งาน

ตอนนี้เมื่อผู้ใช้เลือก "หญิง" อีกครั้งปุ่มส่งจะไม่ถูกปิดใช้งาน

ผู้ใช้ต้องคลิกปุ่มส่งเพื่อที่จะกลับสู่สถานะเดิมและปิดใช้งานปุ่ม

จะรีเซ็ตเป็นสถานะเก่าได้อย่างไรเมื่อผู้ใช้เปลี่ยนค่ากล่องเลือกกลับเป็นค่าเริ่มต้นโดยไม่ต้องคลิกปุ่มส่ง

รุ่นเชิงมุม: 8.2.14.

อัปเดต

เชิงมุมที่น่าเศร้าดูเหมือนจะไม่เปลี่ยนสถานะของฟอร์มเป็นแบบเก่าเมื่อผู้ใช้เปลี่ยน UI เป็นค่าเริ่มต้น

ดังนั้นเราจึงต้องเขียนโค้ดเพื่อทำการเปรียบเทียบข้อมูลและทำเครื่องหมายแบบฟอร์มเพื่อสถานะที่บริสุทธิ์

คำตอบ

2 Chellappanவ Aug 19 2020 at 21:16

คุณสามารถใช้เมธอดmarkAsPristineเพื่อตั้งค่าสถานะpristine true เมื่อข้อมูลเปลี่ยนกลับเป็น defaultValue ดังนี้:

ngOnInit() {
    const defaultValue = this.registrationForm.value;
    this.registrationForm.valueChanges
      .pipe(debounceTime(200))
      .subscribe(value => {
        if (JSON.stringify(defaultValue) == JSON.stringify(value)) {
          this.registrationForm.markAsPristine();
        }
      });
  }
1 MinalShah Aug 19 2020 at 20:59

คุณสามารถสร้างวิธีการหนึ่งที่ส่งคืนค่าจริงหรือเท็จสำหรับการปิดใช้งานปุ่มส่งหากไม่มีอะไรเปลี่ยนแปลง

สมมติว่าคุณมีวัตถุบางอย่างที่ใช้สำหรับเก็บอินพุตของแบบฟอร์ม

อ้างถึงรหัสด้านล่างสำหรับฟังก์ชัน:

oldObj = _.cloneDeep(this.obj)
dataChanged(){
 return !_.isEqual(this.oldObj, this.obj)
}

และใน html ให้เพิ่มบรรทัดด้านล่าง

<input type="submit" [disabled]="!hasChanged()">