angular: directivas estructurales

  • PPT 3.7 + 3.8 + 3.9 + 4.1 + 4.2 + 4.3
  • lógica en capa de presentación (plantilla)
  • se reconocen por tener * en el nombre
  • no es necesario fichero HTML
  • no es un componente
  • elemento que queremos ocultar o mostrar
  • se le asigna algun expresión que retorne un boolean
  • angular crea o descrea el elemento del DOM según marque la variable:
    <div *ngIf="mostrar" class="card text-white bg-primary mb-3" style="max-width: 100%;">
    • mostrar al estar vinculado a la directiva hace referencia a un atributo de la clase, si no, iría entre {{ }}
    • binding de eventos:
      <button (click)="mostrar = !mostrar" class="btn btn-outline-primary btn-block">
  • repite el elemento:
    <li *ngFor="let color of colores" class="list-group-item">{{color}}</li>
    • usamos un array colores defindo en la clas del componente:
      export class BodyComponent {
          mostrar = false;
          colores: string[] = ['rojo','verde','azul'];
          ...
      }
  • se pueden adicionar cosas:
    <li *ngFor="let color of colores; let i=index" class="list-group-item">{{i}} {{color}}</li>

<div *ngIf="numero % 2 == 0; else impar">
    <h1>Número {{ numero }} - Es par</h1>
</div>
<ng-template #impar>
    <h1>Número {{ numero }} - Es impar</h1>
</ng-template>

<div *ngIf="numero % 2 == 0; then par else impar"></div>

<ng-template #par>
    <h1>Número {{ numero }} - Es par</h1>
</ng-template>

<ng-template #impar>
    <h1>Número {{ numero }} - Es impar</h1>
</ng-template>

ng g[enerate] c[component] components/ngSwitch -is --skipTests

...
export class NgSwitchComponent implements OnInit {
    mensaje = 'info';
}
...
<div [ngSwitch]="mensaje">
    <div *ngSwitchCase="'success'">Success</div>
    <div *ngSwitchCase="'info'">Info</div>
    <div *ngSwitchCase="'warning'">Warning</div>
    <div *ngSwitchDefault>Danger</div>
</div>
<button type="button" (click)="mensaje='success'" class="btn btn-primary">Cambiar</button>
<div [ngSwitch]="mensaje">
    <div *ngSwitchCase="'success'" class="alert alert-success" role="alert">
        <strong>Well done!</strong> You successfully read this important alert message!
    </div>
    <div *ngSwitchCase="'info'" class="alert alert-info" role="alert">
        <strong>Heads up!</strong> This alert needs your attention...
    </div>
    <div *ngSwitchCase="'warning'" class="alert alert-warning" role="alert">
        <strong>Warning!</strong> Better check yourself, you're not looking too...
    </div>
    <div *ngSwitchDefault class="alert alert-danger" role="alert">
        <strong>Oh snap!</strong> change a few things up and try submitting again!
    </div>
</div>

  • development/angular/directivas-estructurales.txt
  • Darrera modificació: 09/02/2020 14:51
  • per mate