首页 > 解决方案 > 我们如何将输入值发送到指令

问题描述

我想将输入字段值动态传递给指令。我必须通过指令中的发布请求将该输入值发送到服务器。我怎样才能做到这一点???

我的html代码

     <input type="text" [appHighlight]="appHighlight">

我的指令代码

     import { Directive, ElementRef, Input, Renderer2, HostBinding, TemplateRef, 
     ViewContainerRef, HostListener } from '@angular/core';
     import { NgControl } from '@angular/forms';
     import { HttpClient } from '@angular/common/http';
     import { HelloService } from './hello.service';

     @Directive({
     selector: '[appHighlight]',

     })
    export class HighlightDirective {
    @Input('appHighlight') appHighlight: string;
     constructor(private el: ElementRef, private http: HttpClient, private hello: 
     HelloService ) { }


    @HostListener('keyup.enter') disableInput(val) {
     console.log(val)
    this.hello.postauthorized({"key":this.appHighlight}).subscribe((res)=>{
     console.log(res)
     })

     }
   ngOnInit(){
  console.log(this.appHighlight)
   }

   }

标签: angular

解决方案


您可以通过将 ElementRef 注入指令来获取输入的值:

HTML

<input type="text" appHighlight>

TS

import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private elmt: ElementRef<HTMLInputElement>) {}

  @HostListener('keyup.enter') validate() {
    const value = this.elmt.nativeElement.value;
    /* Do anything you want with this value */
  }
}

跳它有帮助!


推荐阅读