我正在试验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);
}
但是它不能正常工作。打印undefined ..
我关心的是...
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"
是创建一个引用指令的模板变量(requires 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"/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句