angular - 我们如何将输入值发送到指令
问题描述
我想将输入字段值动态传递给指令。我必须通过指令中的发布请求将该输入值发送到服务器。我怎样才能做到这一点???
我的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)
}
}
解决方案
您可以通过将 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 */
}
}
跳它有帮助!
推荐阅读
- javascript - 返回取决于可观察对象的值的最佳和最干净的方法
- cors - 使用“Auth Code Flow + PKCE”时来自令牌端点的 CORS 错误
- openlayers - 如何在 Openlayers 中将 Lon Lat 转换为 Geomtry?
- c# - 如何从 postgres 表中获取数据并将其作为插入查询从 C# 以编程方式存储在文件中?
- python - 模型未显示在使用内置 AbstractUser 创建的 Django Admin 中
- spring-boot - Spring Webflux 抛出“block()/blockFirst()/blockLast() 正在阻塞,线程 reactor-http-nio-2 不支持”
- html - 调整浏览器窗口大小时,此网页变得混乱
- rest - 访问 NFL API
- c# - 如果列大于 1024,如何拆分 DataTable?
- objective-c - 调试区域上的 Swift 中的漂亮打印对象