专注于显示错误消息的文本区域

时间:2019-06-25 09:34:51

标签: angular typescript angular2-services

我使用forloop显示了许多文本区域,并且还检查了文本区域是否包含所需的最小单词数。如果文本框不包含最小单词数,则会显示错误消息。我如何专注于显示错误的文本框

我正在使用角度2

html

 <span *ngSwitchCase="'fileupload_with_textarea'">
               <textarea  autosize [value]='question.value'  class="form-control"    max-word-count maxlen=
               {{question.word_details.maximum_word}} minlen=
               {{question.word_details.minimum_word}}  [formControlName]="question.key"  [id]="question.key" (blur)="focusOutSave(question)" #message></textarea>
                <div class="alert alert-danger" *ngIf="question.controlType == 'fileupload_with_textarea' && page_submit && !form.controls[question.key].valid && form.controls[question.key].touched">You didn't enter the answer.</div>
            </span>

组件

import { Component, Input, Output, OnInit, Directive,AfterViewInit, EventEmitter, ViewChild ,ViewChildren ,ElementRef ,ChangeDetectorRef, HostListener}  from '@angular/core';


@Component({
    selector: 'dynamic-form',
    templateUrl: './dynamic-form.component.html',
    providers: [ QuestionControlService, SweetAlertService],
    styles: [
    `
      :host >>> .tooltip-inner {
        background-color: #f88f5a;
        color: #fff;
        font-weight: bold;
        padding: 5px;
      }
      :host >>> .tooltip.top .tooltip-arrow:before,
      :host >>> .tooltip.top .tooltip-arrow {
        border-top-color: #f88f5a;
      }
    `
  ]
 })


export class DynamicFormComponent implements OnInit {

    @Input() questions: QuestionBase<any>[] = [];

    @Input() input_params: any;
    @Input() other_vars:any;


    @Input() question_loading_status:boolean;
    @Output() outputEvent:EventEmitter<QuestionBase<any>[]>=new EventEmitter();


    @Input() enrolment_detail_id: number;
    @Output() getQuestions  = new EventEmitter();
    @ViewChild('message') public message: ElementRef;


//onsubmit
 if (this.form.controls[question.key]['wordCt'] != undefined) { 
                if(this.form.controls[question.key]['wordCt'].wordFlag == false && wordCountFlag){
                    wordCountFlag = 0;
                    this.message.nativeElement.focus();
                }
                }

1 个答案:

答案 0 :(得分:1)

您可以使用ElementRef来获取对讨厌的HTML元素的引用,并使用它的focus()方法。

在模板组件中:

<textarea
   #messageInput
></textarea>

您的组件:

@ViewChild('messageInput') public messageInput: ElementRef;

在验证代码中,您可以像这样在textarea上调用本机焦点方法:

this.messageInput.nativeElement.focus();