在提交表单上显示模态

时间:2017-10-13 00:07:35

标签: javascript html twitter-bootstrap angular typescript

以下是用于收集访问者联系信息的Angular 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 个答案:

答案 0 :(得分: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.
        }
    });
}

不要忘记从提交按钮中删除数据切换和数据目标属性。

希望这有帮助。