R. *_*Dey 5 angular2-directives angular
我正在试验 angular-2 basic 的自定义指令,我想在我的自定义指令中解析输入值。
我们来看一下。
我有一个名为 app.component.ts 的应用程序组件。我在哪里输入了输入字段。
<input [(ngModel)] = "myInput"/>
Run Code Online (Sandbox Code Playgroud)
接下来我构建一个自定义指令名称 custom.directive.ts
import { Directive, ElementRef, Renderer} from '@angular/core';
@Directive ({
selector : '[customDir]'
})
export class CustomDirective{
constructor(private el : ElementRef, private renderer: Renderer){ }
}
Run Code Online (Sandbox Code Playgroud)
现在我想在“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);
}
Run Code Online (Sandbox Code Playgroud)
但它不能正常工作。打印未定义..
我的担心是...
1...我如何根据每次按键解析数据..?
请给我建议任何人...
@Directive ({
selector : '[customDir]',
exportAs: 'customDir' // <<<=== added
})
export class CustomDirective{
myInput : any;
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它
<input customDir #customDir="customDir" [(ngModel)]="myInputInApp" (ngModelChange)="customDir.myInput = $event"/>
Run Code Online (Sandbox Code Playgroud)
首先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);
}
}
Run Code Online (Sandbox Code Playgroud)
<input customDir [(ngModel)]="someOtherProp"/>
Run Code Online (Sandbox Code Playgroud)