Why would it be interesting to add or remove HTML element from the DOM?

Asked

Viewed 191 times

1

I am starting my studies in Angular 7 and in a class on Structural Directives, I learned that I can add or remove elements HTML of DOM.

I understood that there are 3 main, the ngIf, the ngSwitch and the ngFor.

The ngIf and the ngSwitch are used to conditionally rederizate the elements HTML. The ngFor is used to render a list of elements HTML.

Using the ngIf, I have an example:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  //templateUrl: './test.component.html',
  template: `

    <h2 *ngIf="true">
        Marcielli
    </h2>
  `,
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

NOTE: For study purpose, I am using in the same file.

When ngIf is set to true, on the screen looks like this:

inserir a descrição da imagem aqui

And when it’s set to false, gets like this:

inserir a descrição da imagem aqui

The question is: In what real situation would I use this? For what reason, for example, would I want to remove an element from the DOM?

  • 1

    in dynamic elements, think of a stock control where it can be controlled by und. or weight by item feature vc can apply dynamicity if it is of type und, has such control or even such input, or if it is weight such control or such input

1 answer

3

The question is: In what real situation would I use this? For what reason, for example, would I want to remove an element from the DOM?

In practice there are several examples, I will cite two more used in my day-to-day:

  1. Access level, displays certain parts of html according to the user’s permission level.
  2. Form, add new field, remove or display fields in progress (when the criterion is met displays the next item).

The basic idea would be that the end user could control the form via html. The same could also be done with just one hide() (hide via css), but this would not have the security layer that prevents the user from manipulating all the data via console.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.