Reputation: 107
I'm trying to create a fairly basic directive that can either, hide (remove from DOM), show, or show and disable content inside it depending on user permissions.
As per the angular guide I should be able to do something similar to this to modify content inside a directive.
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
However I am having a problem accessing the inner content of the directive. This needs to be a structural directive in order to be able to remove the content from the DOM, but when I make it a structural directive ElementRef only returns a HTML comment element containing the ng bindings, it does not return the actual content.
When I test this as a non-structural directive it returns the actual content.
How do I access the inner content of a structural directive?
Upvotes: 4
Views: 21809
Reputation: 291
It's possible to catch it as you made. But you have just move the operations in the ngOnInit like this.
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit{
constructor(el: ElementRef) { }
ngOnInit() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}
Upvotes: 0
Reputation:
I think you're mixing them all together.
A structural directive is a directive made to manipulate the DOM itself : it can append or remove a whole section of the DOM based on conditions.
An attribute directive is a directive made to change an element of the DOM. It can change its style, but it can't delete it from the DOM (but can hide it with CSS though).
They have a dedicated purpose and can't (well, shouldn't) try to do what the other is supposed to do. They also have different syntaxes due to their purpose.
If you look at this stackblitz you will see the difference between both : one can display the element reference (attribute), the other will only display an HTML comment (structural).
The structural directive is used in a reserved space in the HTML and is aware only of that space.
If you wish to get the element reference of the element that has the structural directive, you will need to use the nextElementSibling
of the comment to get it.
But then again, just look at the blitz, and see for yourself !
Upvotes: 13
Reputation: 184
Try this
constructor(private elementRef: ElementRef) {}
ngAfterViewInit() {
this.elementRef.nativeElement.style.backgroundColor = 'yellow';
}
Upvotes: 0