问题描述
我成功地使用了 ng bootstrap,特别是模态模块来显示模态表单.这是一个包含电子邮件和消息输入字段以及提交按钮的联系表单.我使用的 ngbootstrap 模块是 https://ng-bootstrap.github.io/#/components/modal/examples 这显示得很好.我想要做的是,当用户单击发送"按钮(请参阅下面的模板代码)时,该按钮将被禁用并说发送...".换句话说,我正在尝试操作属性视图模式组件.
我已经查看了以下问题,但没有任何建议有效:
Angular 2 @ViewChild 注释返回未定义如何在 Angular 2 中获取与 ElementRef 关联的组件的引用
无论如何,当我尝试在我的组件中使用时,我会得到未定义"
@ViewChild('submitButton') submitButton: ElementRef;
连同我模板中的这个 html
这是完整的组件代码(我试图访问submitButton的地方在方法
onSubmit()
中):
导入{零件,初始化,渲染器2,查看孩子,元素参考,AfterViewInit} 来自'@angular/core';从 '@angular/forms' 导入 { FormGroup, FormControl, Validators };从'@ng-bootstrap/ng-bootstrap'导入{ NgbModal, ModalDismissReasons };从'../../services/contact.service'导入{ ContactService};@零件({选择器:'app-contact-modal',模板网址:'./contact-modal.component.html'})导出类 ContactModalComponent 实现 OnInit、AfterViewInit {关闭结果:字符串;联系表格:表格组;//@ViewChild('submitButton') 提交按钮;@ViewChild('submitButton') submitButton: ElementRef;构造函数(私人模态服务:NgbModal,私人联系服务:联系服务,私有渲染器:Renderer2) { }ngOnInit() {this.initForm();}ngAfterViewInit() {console.log(this.submitButton);}私人getDismissReason(原因:任何):字符串{如果(原因 === ModalDismissReasons.ESC){返回'按ESC';} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {return '通过点击背景';} 别的 {返回 `with: ${reason}`;}}私人initForm(){常量电子邮件 = '';常量消息 = '';this.contactForm = new FormGroup({电子邮件:新的 FormControl(空,Validators.email),消息:新的 FormControl(null, Validators.required)});}onSubmit() {常量电子邮件 = this.contactForm.value.email;常量消息 = this.contactForm.value.message;//此时 this.submitButton 是 UNDEFINEDconsole.log(this.submitButton);//this.submitButton.nativeElement.style.backgroundColor = 'black';this.contactService.sendContactRequest(email, message, (submitSuccess: boolean) => {如果(提交成功){console.log('成功更新 UI');this.contactForm.value.email = '';this.contactForm.value.message = '';} 别的 {console.log('错误更新用户界面');}});}打开(内容){console.log('in open func');this.modalService.open(内容,{ariaLabelledBy:'modal-basic-title'}).结果.然后((结果)=>{console.log(`结束于:${result}`);},(原因)=>{console.log(`Dismissed ${this.getDismissReason(reason)}`);});}}
这是我的完整模板:
非常感谢任何帮助.
解决方案
//this.submitButton.nativeElement.style.backgroundColor = 'black';
如果我正确理解了这个问题(和你的代码),你基本上想做三件事:
点击发送后将按钮设置为禁用
将按钮文本设置为正在发送..."
将按钮背景颜色设置为黑色(在您的代码中)
前两个可以通过数据绑定(数据类型绑定).对于第三个,我找到了一种解决方法,让它工作(使用 dom,而不是 angular @Viewchild).
您可以在 typescript 文件中使用布尔变量(例如 ''isDataSent: boolean''),或者在 HTML 中使用 ''!isValid''
您在 .ts 文件中使用变量指定显示的文本,并使用数据绑定来显示它
您通过 id 访问 dom 元素,设置颜色并删除 ''@ViewChild('submitButton') submitButton: ElementRef;'' 行.如果你想通过访问 dom 来做所有的事情,你也可以这样做:-)
这里是示例代码(省略的行可以视为未修改,注释带有)
将 HTML 按钮更改为:
<按钮id="提交按钮";类=btn btn-成功w-100";[已禁用]="!contactForm.valid ||isDataSent">{{submitButtonText}}</button>
所以在打字稿文件中:
导出类 ContactModalComponent 实现 OnInit, AfterViewInit {//... 代码 ...isDataSent:布尔值;提交按钮文本:字符串;//... 代码 ...ngOnInit() {//... 代码 ...this.isDataSent = false;this.submitButtonText = '发送';//... 代码 ...}//... 代码 ...onSubmit() {常量电子邮件 = this.contactForm.value.email;常量消息 = this.contactForm.value.message;const submitButton = document.getElementById('submitButton');如果(提交按钮){submitButton.style.backgroundColor = '黑色';}this.submitButtonText = '发送中...';this.isDataSent = true;this.contactService.sendContactRequest(email, message, (submitSuccess: boolean) => {如果(提交成功){console.log('成功更新 UI');this.contactForm.value.email = '';this.contactForm.value.message = '';} 别的 {console.log('错误更新用户界面');}});}//... 代码 ...}
我正在使用 Angular CLI:11.2.8 和 Node:14.16.0.
希望这会有所帮助,如果您对我的回答有任何改进,请告诉我.
-亚历克斯
I am successfully using ng bootstrap and specifically the modal module to show a modal form. It is a contact form that has email and message input fields and a submit button. The ngbootstrap module I am using is https://ng-bootstrap.github.io/#/components/modal/examples this shows fine. What I am trying to do is that when user clicks on the 'send' button (see template code below) the button will become disabled and say 'sending...'. In other words I'm trying to manipulate the properties view the modal component.
I have already looked at the following questions but none of the suggestions work:
Angular 2 @ViewChild annotation returns undefinedHow to get reference of the component associated with ElementRef in Angular 2
However no matter what, I get 'undefined' when I try to use in my component
@ViewChild('submitButton') submitButton: ElementRef;
along with this html in my template
<button #submitButton
id="submitButton"
class="btn btn-success w-100"
[disabled]="!contactForm.valid"
>Send</button>
Here is the full component code (the place where I am trying to access the submitButton is in method
onSubmit()
):
import {
Component,
OnInit,
Renderer2,
ViewChild,
ElementRef,
AfterViewInit
} from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import { ContactService } from '../../services/contact.service';
@Component({
selector: 'app-contact-modal',
templateUrl: './contact-modal.component.html'
})
export class ContactModalComponent implements OnInit, AfterViewInit {
closeResult: string;
contactForm: FormGroup;
//@ViewChild('submitButton') submitButton;
@ViewChild('submitButton') submitButton: ElementRef;
constructor(
private modalService: NgbModal,
private contactService: ContactService,
private renderer: Renderer2
) { }
ngOnInit() {
this.initForm();
}
ngAfterViewInit() {
console.log(this.submitButton);
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
private initForm() {
const email = '';
const message = '';
this.contactForm = new FormGroup({
email: new FormControl(null, Validators.email),
message: new FormControl(null, Validators.required)
});
}
onSubmit() {
const email = this.contactForm.value.email;
const message = this.contactForm.value.message;
// at this point this.submitButton is UNDEFINED
console.log(this.submitButton);
//this.submitButton.nativeElement.style.backgroundColor = 'black';
this.contactService.sendContactRequest(email, message, (submitSuccess: boolean) => {
if (submitSuccess) {
console.log('SUCCESS UPDATE UI');
this.contactForm.value.email = '';
this.contactForm.value.message = '';
} else {
console.log('ERROR update UI');
}
});
}
open(content) {
console.log('in open func');
this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'})
.result
.then(
(result) => {
console.log(`Closed with: ${result}`);
},
(reason) => {
console.log(`Dismissed ${this.getDismissReason(reason)}`);
}
);
}
}
Here is my full template:
<a
class="nav-link"
(click)="open(content)"
><i class="fas fa-envelope"></i></a>
<ng-template #content let-c="close" let-d="dismiss">
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Contact Us</h4>
<button type="button" class="close" aria-label="Close" (click)="c()">
<i class="fas fa-times"></i>
</button>
</div>
<div class="modal-body">
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<div class="row justify-content-center">
<div class="col-md-12 col-sm-12">
<div class="form-group">
<label for="email">Email</label>
<input
type="text"
class="form-control"
id="email"
formControlName="email"
>
</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-12 col-sm-12">
<div class="form-group">
<label for="message">Message</label>
<textarea
type="text"
class="form-control"
id="message"
formControlName="message"
rows="6"
></textarea>
</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-12 col-sm-12">
<button #submitButton
id="submitButton"
class="btn btn-success w-100"
[disabled]="!contactForm.valid"
>Send</button>
</div>
</div>
<div class="row">
<div class="col-md-12 col-sm-12">
<div *ngIf="sentMessage" class="alert alert-success" role="alert">
{{ sentMessage }}
</div>
</div>
</div>
</form>
</div>
</ng-template>
Any help is greatly appreciated.
解决方案
if I understand the question (and your code) correctly, you basically want to do three things:
Set button to disabled after clicking on send
Set button text to ''sending...''
Set button background color to black (in your code)
You can do the first two by data binding (Types of data binding).For the third one I found a workaround, to get it working (using the dom, instead of angular @Viewchild).
You can use a boolean-variable in the typescript file (e.g. ''isDataSent: boolean'') which you OR with the ''!isValid'' in the HTML
You specify the displayed text in the .ts file with a variable and use Data Binding to show it
You access the dom element by id, set the color and remove the ''@ViewChild('submitButton') submitButton: ElementRef;'' line. If you want to do all the things by accessing the dom, you can do it also this way :-)
Here is sample code (which lines omitted can be seen as untouched, comments with )
Change the HTML-Button to:
<button
id="submitButton"
class="btn btn-success w-100"
[disabled]="!contactForm.valid || isDataSent"
>{{submitButtonText}}</button>
So in the typescript file:
export class ContactModalComponent implements OnInit, AfterViewInit {
// ... code ...
isDataSent: boolean;
submitButtonText: string;
// ... code ...
ngOnInit() {
//... code ...
this.isDataSent = false;
this.submitButtonText = 'Send';
//... code ...
}
// ... code ...
onSubmit() {
const email = this.contactForm.value.email;
const message = this.contactForm.value.message;
const submitButton = document.getElementById('submitButton');
if (submitButton) {
submitButton.style.backgroundColor = 'black';
}
this.submitButtonText = 'sending...';
this.isDataSent = true;
this.contactService.sendContactRequest(email, message, (submitSuccess: boolean) => {
if (submitSuccess) {
console.log('SUCCESS UPDATE UI');
this.contactForm.value.email = '';
this.contactForm.value.message = '';
} else {
console.log('ERROR update UI');
}
});
}
//... code ...
}
I'm using Angular CLI: 11.2.8 and Node: 14.16.0.
Hope this helps, if you have any improvements on my answer, please let me know.
-Alex
这篇关于@ng-bootstrap/ng-bootstrap NgbModalModule 模态中的 Angula6 ViewChild 返回 undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!