Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide elements using Typescript

I'm new to Typescript and Angular Material. I want to hide elements inside elements like this.

<div id="abc">
   <div id="123">
      <p>Hello!</p>
   </div>
      <p>World</p>
</div>
<div id="def">
    <p>Hello World</p>
</div>

I want to hide div block(id:123).I tried in this way.

var formElement = <HTMLFormElement>document.getElementById('123');
formElement.style.display='block';

It gets an error saying Cannot read property 'style' of null.... How can I solve this problem.

like image 851
JanithCW Avatar asked Jan 04 '18 17:01

JanithCW


2 Answers

This is not the way to hide elements in Angular. Bind your element's style attribute to a boolean, like this:

<form [style.display]="isVisible ? 'block' : 'none'">... contents</form>

And in your component class:

this.isVisible = false; // whenever you need to hide an element

Or you can use *ngIf:

<form *ngIf="isVisible">... contents</form>

Please, note that *ngIf removes the node and its children completely from the DOM tree completely if the conditions turns to false, and fully recreates them from scratch when the condition turns true.

like image 108
Armen Vardanyan Avatar answered Oct 18 '22 13:10

Armen Vardanyan


@Component({
  selector: 'my-app',
  template: `
   <div #id>
      <p>Hide This!</p>
   </div>
<div>
    <p>Hello World</p>
</div>
  `,
})
export class AppComponent {    
@ViewChild('id') id:ElementRef;
  constructor() {}
  ngOnInit()
  {
     this.id.nativeElement.hidden=true;
  }
}
like image 24
Kalakar Avatar answered Oct 18 '22 13:10

Kalakar