Issue
I'm trying to implement malarkey as an Angular2 pipe. The idea is that you'll be able to write an expression like ['foo','bar','baz'] | malarkey
and get the typing effect. Malarkey needs to select the parent element, so I want to set up my pipe to grab the ElementRef and pass the selector through to malarkey:
import { Pipe, PipeTransform, ElementRef } from '@angular/core';
declare var malarkey: any;
@Pipe({
name: 'malarkey'
})
export class MalarkeyPipe implements PipeTransform {
...
elem: HTMLElement;
constructor(el: ElementRef) {
this.elem = el.nativeElement;
}
transform(value: [string], args?: {}): any {
if (!value) return value;
var elem = this.elem;
let opts = {
...
};
let act = malarkey(elem,opts);
return value.forEach(function(w) {
act.type(w).pause().delete();
});
}
}
I get an exception: No provider for ElementRef!
What's happening here?
Solution
The elementRef isn't available for injection at the level of the pipe. Only for components and corresponds to the root element of the component.
That being said, you could provide an elementRef as input of your pipe. Here is a sample:
@Pipe({
name: 'malarkey'
})
export class MalarkeyPipe implements PipeTransform {
...
transform(value: [string], elem:ElementRef): any {
if (!value) return value;
var elem = this.elem.nativeElement;
let opts = {
...
};
let act = malarkey(elem,opts);
return value.forEach((w) => {
act.type(w).pause().delete();
});
}
}
You can use it this way:
['foo','bar','baz'] | malarkey:elementRef
To get the elementRef within the component, you can inject it in the constructor (root element) or leverage the ViewChild
decorator:
@Component({
template: `
<div>
<div #test>Some div</div>
</div>
`
})
export class SomeComponent {
@ViewChild('test')
elementRef:ElementRef;
}
Answered By - Thierry Templier
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.