[英]How to send input data value into custom directive in angular-2?
我正在试验angular-2 basic的自定义指令,我想在我的自定义指令中解析输入值。
我们来看一下。
我有一个名为app.component.ts的应用程序组件。 我在哪里采取了输入字段。
<input [(ngModel)] = "myInput"/>
接下来,我构建一个自定义指令名称custom.directive.ts
import { Directive, ElementRef, Renderer} from '@angular/core';
@Directive ({
selector : '[customDir]'
})
export class CustomDirective{
constructor(private el : ElementRef, private renderer: Renderer){ }
}
现在我想在“app.component.ts中输入任何内容并在我的自定义指令中解析它,我可以通过它在控制台中简单地打印它。
让我们重新修改我的代码......
<app.component.ts>
<input [(ngModel)] = "myInput" [customDir] = "myInput"/>
<custom.directive.ts>
import { Directive, ElementRef, Renderer, Input} from '@angular/core';
@Directive ({
selector : '[customDir]'
})
export class CustomDirective{
@Input('customDir') myInput : any;
constructor(private el : ElementRef, private renderer: Renderer){ }
console.log(this.myInput);
}
但它不能正常工作。 印刷无法定义..
我的担忧是......
1 ...我如何针对每个按键解析数据..?
请建议我任何人......
@Directive ({
selector : '[customDir]',
exportAs: 'customDir' // <<<=== added
})
export class CustomDirective{
myInput : any;
}
并使用它
<input customDir #customDir="customDir" [(ngModel)]="myInputInApp" (ngModelChange)="customDir.myInput = $event"/>
第一个customDir
是根本应用指令。
#customDir="customDir"
用于创建一个模板变量,该变量具有对该指令的引用(需要exportAs
)
[(ngModel)]="customDir.myInput"
绑定到模板变量#customDir
引用的指令及其属性input
。 这种情况下不需要@Input()
,因为它不是此处使用的Angular绑定。
这应该也可以使用,更容易使用:
@Directive ({
selector : '[customDir]',
})
export class CustomDirective{
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
console.log(event);
}
}
<input customDir [(ngModel)]="someOtherProp"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.