Home > Net >  Angular add dom element after current input in directive
Angular add dom element after current input in directive

Time:08-14

I have two inputs:

      <label for="date-string">String value</label>
      <input [formControl]="dateString" type="date" id="date-string"/>
      <br>
      <label for="date-object">Date object with directive help</label>
      <input [formControl]="dateObject" type="date" id="date-object"/>

I want to add a div straight after an input using a directive for all inputs type 'date' and have 'formControl' directive.

The only problème is how to add a dom element after current html element (using elementRef). I've seen ppl talking about parent node, but i don't want to appendChild to the parent node (the new element will be at the very end of the node list but i need it to be straight after current input element).

Any idea?

CodePudding user response:

  <div *mydirective>
      <label for="date-string">String value</label>
      <input [formControl]="dateString" type="date" id="date-string"/>
  </div>
  <br>
  <label for="date-object">Date object with directive help</label>
  <input [formControl]="dateObject" type="date" id="date-object"/>
import { DOCUMENT } from '@angular/common';
@Directive({
  selector: '[mydirective']
})
export class MyDirective implements OnInit {
  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document) { }

  ngOnInit() {
    const child = this.document.createElement('div');
    this.renderer.appendChild(this.elementRef.nativeElement, child);
  }
}

So with css/sass techniques to can set the appropriate position for your new element

CodePudding user response:

You can break this down into two questions:

Q1: How to apply a directive to all input elements with type="date" and with the attribute formControl?

A1: When declaring a directive you can use any CSS selector to choose which elements the directive is applied to: https://angular.io/api/core/Directive#options

Q2: How to insert a div immediately after another element?

A2: Use insertBefore applied to the element's next sibling: https://stackoverflow.com/a/4793630/12914833

So the directive looks like this:

@Directive({
  selector: 'input[type="date"][formControl]',
})
export class DateInputDirective {
  constructor(private elRef: ElementRef) {
    const el = elRef.nativeElement as HTMLElement;
    const div = document.createElement('div');
    div.textContent = 'Inserted Div';
    div.style.backgroundColor = 'red';
    // any other styling
    el.parentNode.insertBefore(div, el.nextSibling);
  }
}

Stackblitz: https://stackblitz.com/edit/angular-ivy-n4ault?file=src/app/date-input.directive.ts

  • Related