Home > Enterprise >  How to pass referent to component or dom element?
How to pass referent to component or dom element?

Time:05-31

There is a component with dom element inside. I need to get reference to this component in service. How to do that? Passing id of dom element, create a reference as component or use elementref?

It needs to be able show hide this component

CodePudding user response:

as I understand

import { Component, ViewChild, ElementRef, AfterViewInit, Renderer2 } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <div>
    <input ngModel #username>
    <p>{{ username.value }}</p>
  </div>
  `
})
export class AppComponent implements AfterViewInit {
  @ViewChild('username') input: ElementRef<HTMLInputElement>;

  constructor(private renderer: Renderer2) {}
  
  ngAfterViewInit() {
    // ElementRef: { nativeElement: <input> }
    console.log(this.input);

    // Access the input object or DOM node
    console.dir(this.input.nativeElement);

    // Manipulate via Renderer2
    this.renderer.setStyle(this.input.nativeElement, 'background', '#d515a0');
  }
}

an element referernce looks like this :

class ElementRef<T> {
  constructor(nativeElement: T)
  nativeElement: T
}
  • Related