2016-11-19 36 views
0

我正在爲網站做一個配置文件頁面。頁面底部有一個提交按鈕。當用戶查看頁面時,提交按鈕被禁用,因爲沒有任何改變。Angular2在HTTP POST請求中禁用後重新啓用提交按鈕

當某些內容被修改且其有效時,該按鈕將是可點擊的。然後在通過HTTP Post提交後,如果成功,則會有一個標誌使其不可點擊,並且會向用戶顯示成功消息。以上的一切都很好。

但是,當用戶再次更改內容時會出現問題。因爲曾經有一個標誌,並且該標誌始終禁用該按鈕。 所以要解決這個問題,我認爲可能有兩種方法。一種是一旦內容再次改變就切換標誌。一種是以完全不同的方式禁用按鈕。但我不知道如何做任何一個。

TS代碼:

@Component({ 
    moduleId: module.id, 
    selector: 'profile', 
    templateUrl: 'profile.component.html', 
}) 
export class ProfileComponent{ 
    name: string; 
    email: string; 
    updateSucc : boolean = false; 
    profileForm : FormGroup; 

    constructor(fb: FormBuilder, private http:Http) { 

    this.profileForm = fb.group({ 
     'name' : ['', Validators.required], 
     'email': [''], 
    }) 

    submitForm(value: any){ 

    let form = { 
     'updates': { 
     'name' : value.name 
     } 
    } 

    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers, 
            withCredentials: true }); 

    this.http.post('http://SERVER.API?email='+localStorage.getItem('email'), form, options).subscribe(
     (res:any)=>{ 
      this.updateSucc = true; 
      }, 
     error => { 
      console.log(error); 
      this.backendService.checkLogIn(error.status); 
     } 
    ) 
    } 
} 

HTML代碼:

<div class="container"> 
<h1>Profile</h1> 
    <div *ngIf = "updateSucc" class="alert alert-success"> 
    Update successful! 
    </div> 
<form [formGroup]="profileForm" (ngSubmit)="submitForm(profileForm.value)"> 
    <div class="form-group" 
    [ngClass]="{'has-error':!profileForm.controls['name'].valid && profileForm.controls['name'].touched}" 
    > 
    <label for="name">Name</label> 
    <input type="text" class="form-control" id="name" 
    [formControl]="profileForm.controls['name']" 
    [(ngModel)] = 'name' name = 'name' 
    > 
    </div> 

    <div class="form-group" 
    [ngClass]="{'has-error':!profileForm.controls['email'].valid && profileForm.controls['email'].touched}" 
    > 
    <label for="email">Email</label> 
    <input type="text" class="form-control" id="email" 
    [formControl]="profileForm.controls['email']" 
    [(ngModel)] = 'email' name = 'email' 
    readonly 
    > 
    </div> 
    <button type="submit" class="btn btn-default" 
      [disabled]="!profileForm.valid 

         || !(profileForm.controls['name'].dirty 
         || profileForm.controls['email'].dirty 
         ) 
         || updateSucc 

      ">Submit</button> 
</form> 
</div> 

可變updateSucc是該標誌。

回答

0

我知道表單首次出現時可能包含一些內容(我們稱之爲原始內容)。 當用戶以有效的方式更改表單數據(以便啓用按鈕)時應用程序應該如何運行,然後再次更改並重置原始內容?

如果在這種情況下,按鈕必須被禁用,則需要將[disabled]屬性鏈接到該比較原始內容(其必須被存儲在一個變量中ngOnInit)與以下形式的當前內容的方法。

否則我會保持你的實現(也許從改變你的可變標誌的名稱updateSuccsubmitButtonDisabled),並將該標誌的值設置爲true與形式的onChange事件觸發的onChange()方法。

我希望這可以幫助