【问题标题】:Angular2: How to enable save button if any model value changed on edit pageAngular2:如果在编辑页面上更改了任何模型值,如何启用保存按钮
【发布时间】:2017-11-13 14:19:13
【问题描述】:

我是 Angular 2 的新手。我有一个页面,我们可以在其中编辑客户资料的详细信息。如果 的任何属性已更改,如何启用保存按钮。我知道使用 $watch 可以在 angular1 中使用。

【问题讨论】:

    标签: angular2-template angular2-components


    【解决方案1】:

    这很简单。 dirty 如果您使用的是@angular/forms,请检查您的表单。

    创建表单

    export class HeroDetailComponent4 {
      heroForm: FormGroup;
      states = states;
    
      constructor(private fb: FormBuilder) {
        this.createForm();
      }
    
      createForm() {
        this.heroForm = this.fb.group({
          name: ['', Validators.required ],
          street: '',
          city: '',
          state: '',
          zip: '',
          power: '',
          sidekick: ''
        });
      }
    }
    

    HTML:

        <h2>Hero Detail</h2>
        <h3><i>A FormGroup with multiple FormControls</i></h3>
        <form [formGroup]="heroForm" novalidate>
    <button (click)="submit()" [disabled]="!heroForm.dirty" type="button">Submit</button>
          <div class="form-group">
            <label class="center-block">Name:
              <input class="form-control" formControlName="name">
            </label>
          </div>
          <div class="form-group">
            <label class="center-block">Street:
              <input class="form-control" formControlName="street">
            </label>
          </div>
          <div class="form-group">
            <label class="center-block">City:
              <input class="form-control" formControlName="city">
            </label>
          </div>
          <div class="form-group">
            <label class="center-block">State:
              <select class="form-control" formControlName="state">
                  <option *ngFor="let state of states" [value]="state">{{state}}</option>
              </select>
            </label>
          </div>
          <div class="form-group">
            <label class="center-block">Zip Code:
              <input class="form-control" formControlName="zip">
            </label>
          </div>
          <div class="form-group radio">
            <h4>Super power:</h4>
            <label class="center-block"><input type="radio" formControlName="power" value="flight">Flight</label>
            <label class="center-block"><input type="radio" formControlName="power" value="x-ray vision">X-ray vision</label>
            <label class="center-block"><input type="radio" formControlName="power" value="strength">Strength</label>
          </div>
          <div class="checkbox">
            <label class="center-block">
              <input type="checkbox" formControlName="sidekick">I have a sidekick.
            </label>
          </div>
        </form>
    

    使用heroForm.dirty检查表单数据是否改变。如果heroForm 中的任何控件已更改,它将设置为true

    <button (click)="submit()" [disabled]="!heroForm.dirty" type="button">Submit</button>
    

    更多信息请参考angular docs

    【讨论】:

      【解决方案2】:

      您可以对其使用表单控件验证。 html模板中的一些类似的东西:

       <form fxLayout="column" [formGroup]="form">
                <mat-form-field class="mb-1">
                  <input matInput [(ngModel)]="userProfileChangeModel.firstName" placeholder="نام"
                         [formControl]="form1.controls['fname']">
                  <small *ngIf="form1.controls['fname'].hasError('required') && form1.controls['fname'].touched"
                         class="mat-text-warn">لطفا نام را وارد نمایید.
                  </small>
                  <small *ngIf="form1.controls['fname'].hasError('minlength') && form1.controls['fname'].touched"
                         class="mat-text-warn">نام باید حداقل 2 کاراکتر باشد.
                  </small>
                  <small *ngIf="form1.controls['fname'].hasError('pattern') && form1.controls['fname'].touched"
                         class="mat-text-warn">لطفا از حروف فارسی استفاده نمائید.
                  </small>
      
                </mat-form-field>
                 <mat-card-actions>
                  <button mat-raised-button (click)="editUser()" color="primary" [disabled]="!form1.valid" type="submit">
                    ذخیره
                  </button>
                </mat-card-actions>
              </form>
      

      在 ts 文件中像这样:

          this.form = this.bf.group({
        fname: [null, Validators.compose([
          Validators.required,
          Validators.minLength(2),
          Validators.maxLength(20),
          Validators.pattern('^[\u0600-\u06FF, \u0590-\u05FF]*$')])],
      });
      

      如果:

      [disabled]="!form1.valid"
      

      有效的保存按钮将处于活动状态

      问候。

      【讨论】:

        【解决方案3】:

        您可以使用如下所示的禁用选项:

          <button [disabled]="isInvalid()" type="button" (click) = "searchClick()" class="button is-info">
                  <span class="icon is-small">
                    <i class="fa fa-search" aria-hidden="true"></i>
                  </span>
                  <span>Search</span>
             </button>
        

        您可以在 ts 文件中创建 isInvalid() 并检查该属性是否为空并返回该布尔值

        【讨论】:

        • 我有以下组件,如果名称/地址或邮政编码发生更改,我想启用提交按钮。导出类客户实现 OnInit { name: string;地址:字符串;邮编:字符串;构造函数() {} ngOnInit() {} }
        【解决方案4】:

        对于隐藏状态的按钮,您可以使用 *ngIf in line 指令。

        【讨论】:

          【解决方案5】:

          这对我有用,请尝试。 在您的 html 中,

          <input type="text" [ngModel]="name" (ngModelChange)="changeVal()" >
          <input type="text" [ngModel]="address" (ngModelChange)="changeVal()" >
          <input type="text" [ngModel]="postcode" (ngModelChange)="changeVal()" >
          
          <button [disabled]="noChangeYet" (click)="clicked()" >
            <span>SUBMIT</span>
          </button>
          

          在你的组件中

          export class customer implements OnInit { 
            name: string; 
            address: string; 
            postcode: string;
            noChangeYet:boolean = true;
          
            constructor() {} 
          
            changeVal(){ // triggers on change of any field(s)
              this.noChangeYet = false;
            }
          
            clicked(){
              // your function data after click (if any)
            } 
          }
          

          希望这是你需要的。

          【讨论】:

          • 谢谢维娜!是否可以在没有 (ngModelChange)="changeVal()" 的情况下执行此操作,因为我有许多控件并且不想为所有控件添加它。
          • @VindhyachalKumar 您是否使用任何表单或表单组来绑定所有这些输入字段?还是所有这些输入字段都是独立的?
          【解决方案6】:

          我终于解决了这个问题。

          import { Component, Input, Output, OnInit, AfterViewInit, EventEmitter, ViewChild } from '@angular/core';
          
          @Component({
            selector: 'subscribe-modification',
            templateUrl: './subscribe.component.html'
          })
          
          export class SampleModifyComponent implements OnInit, AfterViewInit {
          disableSaveSampleButton: boolean = true;
          @ViewChild('sampleModifyForm') sampleForm;
          
          ngAfterViewInit() {
              setTimeout(() => {
                      this.sampleForm.control.valueChanges.subscribe(values => this.enableSaveSampleButton());
              }, 1000);
          }
          
          enableSaveSampleButton() {
              console.log('change');
              this.disableSaveSampleButton = false;
             }
          }
          
          
          
          HTML
          <button id="btnSave" class="btn btn-primary" (click)="save()" />
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-01-02
            • 2021-06-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-08-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多