Angular2:如果在编辑页面上更改了任何模型值,如何启用保存按钮

时间:2017-11-13 14:19:14

标签: angular2-template angular2-components

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

6 个答案:

答案 0 :(得分:2)

很简单。如果您使用的是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检查表单数据是否已更改。如果true内的任何控件都已更改,它将设置为heroForm

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

有关详细信息,请参阅angular docs

答案 1 :(得分:1)

您可以使用表单控件验证。 在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"

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

bast问候。

答案 2 :(得分:0)

您可以使用以下禁用选项:

# winsorize (default based on 5 x interquartile range)
v <- c(1:4, 99)
winsorize(v)
winsorize(v, replace = NA)
winsorize(v, probs = c(0.01, 0.99))
winsorize(v, cutpoints = c(1, 50))

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

答案 3 :(得分:0)

并且对于状态的隐藏按钮,您可以在行指令中使用* ngIf。

答案 4 :(得分:0)

这对我有用,请试试。 在你的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)
  } 
}

希望这就是你所需要的。

答案 5 :(得分:0)

最后我解决了这个问题。

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()" />