我正在试验 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"
绑定(bind)到模板变量 #customDir
及其属性 input
引用的指令. @Input()
在这种情况下不是必需的,因为这里使用的不是 Angular 绑定(bind)。
这应该也能工作并且更容易使用:
@Directive ({
selector : '[customDir]',
})
export class CustomDirective{
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
console.log(event);
}
}
<input customDir [(ngModel)]="someOtherProp"/>
关于angular - 如何将输入数据值发送到 angular-2 中的自定义指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40417633/