2017-10-13 86 views
2

這裏有一個角4組件用於收集訪問者的聯繫信息代碼:顯示模態上提交表單

的.html:

<form (submit)="onCreateContact()"> 
    <div class="form-group"> 
     <input type="text" [(ngModel)]="contactname" name="contactname" class="form-control form-control-lg" placeholder="Name"> 
    </div> 
    <div class="form-group"> 
     <input type="email" [(ngModel)]="contactemail" name="contactemail" class="form-control form-control-lg" placeholder="Email"> 
    </div> 
    <div class="form-group"> 
     <input type="text" [(ngModel)]="contactphone" name="contactphone" class="form-control form-control-lg" placeholder="Phone"> 
    </div> 
    <input type="submit" class="btn btn-outline-light btn-block" data-toggle="modal" data-target='#addContactModal'> 
</form> 

<!-- Modal --> 
<div class="modal fade" id="addContactModal" tabindex="-1" role="dialog" aria-labelledby="addContactModalLabel" aria-hidden="true"> 
    <div class="modal-dialog" role="document"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <h5 class="modal-title" id="addContactModalLabel">Contact</h5> 
       <button type="button" class="close" data-dismiss="modal" aria-label="Close"> 
        <span aria-hidden="true">&times;</span> 
       </button> 
      </div> 
      <div class="modal-body"> 
       Thanks for contacting us! We will get in touch with you shortly. 
      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button> 
      </div> 
     </div> 
    </div> 
</div> 

.TS:

onCreateContact() { 
    let contact = { 
     contactname: this.contactname, 
     contactemail: this.contactemail, 
     contactphone: this.contactphone 
    } 

    return this.http.post('api/contacts/add', contact).map(res => res.json()).subscribe(data => { 
     if(data.success) { 
      console.log(data); 
     } else { 
      console.log('Failed to add contact'); 
      } 
     } 
    ); 
} 

所有聯繫方式是必填項;如果不是所有字段都被填充,數據不會傳遞到後端。 目前,每次按下提交按鈕時,Bootstrap模式彈出窗口,即使數據未通過。我只能在數據實際傳遞給服務器時才顯示它?

回答

1

當用戶點擊提交按鈕時,您正在切換模式。

您需要做的是在從後端獲取響應後,從組件類(.ts)切換模態。

因此,在你「的.ts」文件中添加下面一行

declare var $: any; 

然後切換模式從後端接收響應如下任後在進口部分

onCreateContact() { 
    return this.http.post('api/contacts/add', contact).map(res => res.json()).subscribe(data => { 
     if(data.success) { 
      console.log(data); 
      $('#addContactModal').modal('show'); // Add this line 
     } else { 
      console.log('Failed to add contact'); 
      $('#errorModalId').modal('show'); // If you are planning to show error modal when something goes wrong. 
     } 
    }); 
} 

不要忘記刪除數據 - 從提交按鈕中選擇 - 數據 - 目標屬性。

希望這會有所幫助。