How to add some html elements using Angular2's attribute directive
15,957
Solution 1
Your code is not valid, so here is an update:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appLoading]'
})
export class LoadingDirective {
constructor(private elementRef:ElementRef){
this.elementRef.nativeElement.innerHTML ='<h1>Hello World2</h1>';
}
}
Solution 2
you directive implementation looks incomplete. you have to bind your directive to any event like click
, focus
etc in order to consume that directive.
import { Directive, ElementRef } from "@angular/core";
@Directive({
selector: "[can-delete]"
})
export class canDelete {
constructor(private _el: ElementRef, private _renderer : Renderer) {
}
@HostListener('mouseenter') onMouseEnter() {
this._renderer.createElement(this._el.nativeElement.parentNode, 'button');
}
}
we are using createElement
method to create button when user hover over element containing our directive. hope it helps!
EDIT : have a look at renderer
createElement
example here for more info.
Author by
user1275105
Updated on June 13, 2022Comments
-
user1275105 almost 2 years
If a certain
attribute directive
is present on an HMTL element, I would like to show some additional html content. I have searched but can't find what am looking for. For example if P tag has a directive calledcan-delete
, then I would like delete button to show.<p can-delete>Hello World!</p>
This is what I got so far:
// >>> home.ts import { Component } from "@angular/core"; import {canDelete } from "./can-delete.directive.ts"; @Component({ templateUrl:"home.html", directives: [canDelete] }) export class HomePage { constructor() { } } // >>> home.html <ion-header> <ion-navbar primary> <ion-title> Ionic 2 </ion-title> </ion-navbar> </ion-header> <ion-content> Content... <p can-delete>Hello World!</p> </ion-content> // >>> can-delete.directive.ts import { Directive, ElementRef } from "@angular/core"; @Directive({ selector: "[can-delete]" }) export class canDelete { constructor(el: ElementRef) { //show delete button //<button>Delete</button> } }