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 called can-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>
}
}
Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility, style your application dynamically, and manage multiple CSS classes or styles simultaneously.
Directives are the functions which will execute whenever Angular compiler finds it. Angular Directives enhance the capability of HTML elements by attaching custom behaviors to the DOM.
Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components. Adds and removes a set of CSS classes. Adds and removes a set of HTML styles. Adds two-way data binding to an HTML form element.
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>';
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With