角度形式的可观察值

时间:2018-07-25 10:00:25

标签: angular angular-forms angular-observable

我的网站上有一个表格(person.firstName,lastName,DOB,性别,公民身份等)。我的问题是我如何观察整个表格的变化并从观察中得到2件事:

  • formControl及其当前状态
  • 已处理formControl的当前值

                                    字首                            {{availablePrefix}}                                       

          <div class="col">
            <label for="firstName">First Name<span style="color: red"> *</span> </label>
            <input formControlName="party.firstName" type="text" autocomplete="off" id="firstName"/>
          </div>
    
          <div class="col">
            <label for="middleName">Middle Name</label>
            <input formControlName="party.middleName" type="text" autocomplete="off" id="middleName" maxlength="1" />
          </div>
    
          <div class="col">
            <label for="lastName">Last Name<span style="color: red"> *</span> </label>
            <input formControlName="party.lastName" type="text" autocomplete="off" id="lastName"/>
          </div>
    
          <div class="col">
            <label for="suffix">Suffix</label>
            <select formControlName="party.suffix" id="suffix">
              <option [value]="availableSuffix" *ngFor="let availableSuffix of availableSuffixes">{{availableSuffix}}
              </option>
            </select>
          </div>
        </div>
      </form>
    

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

valueChanges始终可以观察到,将推送表单的新值。

为了跟踪表单的状态,有几个属性:

status控件的验证状态。有四个可能的验证状态值(VALID , INVALID , PENDING, DISABLED)。

还有另一个可观察到的状态更改状态更改

其他只读布尔属性,用于跟踪表单的状态:

({valid , invalid , pending , disabled , enabled , pristine , dirty , touched , untouched

您可以通过此技巧来跟踪旧的valeu状态

  public form:FormGroup;
  oldValue:any;
  constructor (fb:FormBuilder) { 
     this.form = fb.group({
       name:[],
       lastName:[]
     });

     this.form.valueChanges.subscribe(newValue => { 
        console.log('old value',this.oldValue);
        this.oldValue = newValue;
        console.log('new form value',newValue);
        console.log('state ', this.form.status);
        console.log('pristine ',this.form.pristine);
        console.log('dirty ',this.form.dirty);
        console.log('touched ',this.form.touched);
     });
  }

stackblitz example

AbstractControl

答案 1 :(得分:1)

一旦创建了表单(通过FormBuilder),只需将其写为:

this.fmdForm.valueChanges.subscribe(formValue => { console.log(formValue); });