Τετάρτη 6 Μαΐου 2020

Dynamic CSS with Angular ViewChild, Renderer2








Control element CSS programmatically with ViewChild and Renderer2


1. Input is visible initially

2. Input is hidden with ViewChild




1. Component - HTML


<div>
    Container...
    <div #elementRef>
        <input matInput type="text" value="some data.."/>
        <button mat-button>&nbsp;</button>
    </div>

</div>





2. Component - TS


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

@Component({
  selector: 'jhi-test-comp',
  templateUrl: './test-comp.component.html',
  styleUrls: ['./test-comp.component.scss']
})
export class TestCompComponent implements OnInit,AfterViewInit {

  @ViewChild('elementRef', { static: false })
  elementRef?: ElementRef;

  constructor(private renderer: Renderer2) { }

  ngOnInit(): void {}

  ngAfterViewInit(): void {
    if (this.elementRef) {
      this.renderer.setStyle(this.elementRef.nativeElement, 'display', 'none');
    }
  }
}


Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

What may be missing, or could get better?