Detailed explanation of Angular structural directive modules and styles

Detailed explanation of Angular structural directive modules and styles

1. Structural instructions

* is a syntax sugar, <a *ngIf="user.login">logout</a> is equivalent to

<ng-template [ngIf]="user.login">

<a>Exit</a>

</ng-template>

Avoid writing ng-template.

<ng-template [ngIf]="item.reminder">
      <mat-icon>
        alarm
      </mat-icon>
    </ng-template>
    
    <!-- <mat-icon *ngIf="item.reminder">
      alarm
    </mat-icon> -->

Why can structural instructions change the structure?

ngIf source code

The set method is marked as @Input. If the condition is true and there is no view, the internal hasView flag is set to true and a child view is created according to the template through viewContainer.

If the condition is not true, the view container is cleared of its contents.

viewContainerRef: container, the container of the view where the instruction is located

Module

What is a module? A collection of files with independent functions, used to organize files.

Module metadata

entryComponents: Loaded immediately upon entering the module (such as a dialog box), rather than when called.

exports: If you want to make the internal contents of the module public, you must export them.

What is forRoot()?

imports: [RouterModule.forRoot(routes)],

imports: [RouterModule.forChild(route)];

In fact, forRoot and forChild are two static factory methods.

constructor(guard: any, router: Router);
    /**
     * Creates a module with all the router providers and directives. It also optionally sets up an
     * application listener to perform an initial navigation.
     *
     * Options (see `ExtraOptions`):
     * * `enableTracing` makes the router log all its internal events to the console.
     * * `useHash` enables the location strategy that uses the URL fragment instead of the history
     * API.
     * * `initialNavigation` disables the initial navigation.
     * * `errorHandler` provides a custom error handler.
     * * `preloadingStrategy` configures a preloading strategy (see `PreloadAllModules`).
     * * `onSameUrlNavigation` configures how the router handles navigation to the current URL. See
     * `ExtraOptions` for more details.
     * * `paramsInheritanceStrategy` defines how the router merges params, data and resolved data
     * from parent to child routes.
     */
    static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule>;
    /**
     * Creates a module with all the router directives and a provider registering routes.
     */
    static forChild(routes: Routes): ModuleWithProviders<RouterModule>;
}

The metadata will change according to different situations. There is no way to specify metadata dynamically. Do not write metadata. Directly construct a static engineering method and return a Module.

Write a forRoot()

Create a serviceModule:$ ng gm services

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class ServicesModule { }

The metadata in ServiceModule is no longer needed. Returned by a static method forRoot.

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule()
export class ServicesModule { 
  static forRoot():ModuleWithProviders{
    return {
      ngModule: ServicesModule,
      providers:[]
    }
  }
}

Use when importing in core Module

imports: [ServicesModule.forRoot();]

3. Style Definition

ngClass, ngStyle and [class.yourclass]

ngClass: Used to dynamically specify style classes under certain conditions. It is suitable for situations where a large number of style changes are made. Pre-defined classes.

<mat-list-item class="container" [@item]="widerPriority" [ngClass]="{
  'priority-normal':item.priority===3,
  'priority-important':item.priority===2,
  'priority-emergency':item.priority===1
}"

ngStyle: Used to dynamically specify styles under certain conditions, suitable for situations where there are small changes. For example, in the following example [ngStyle]="{'order':list.order}". key is a string.

[class.yourclass] :[class.yourclass] = "condition" directly corresponds to a condition. This condition is met to apply this class. It is equivalent to the writing of ngClass, which is equivalent to a variant and abbreviation of ngClass.

<div class="content" mat-line [class.completed]="item.completed">
    <span [matTooltip]="item.desc">{{item.desc}}</span>
</div>

Use ngStyle to adjust the order when dragging

The principle is to dynamically specify the order of the flex container style as the order in the list model object.

1. Add order to app-task-list in taskHome

list-container is a flex container, and its arrangement order is sorted according to order.

<app-task-list *ngFor="let list of lists" 
  class="list-container"
  app-droppable="true"
  [dropTags]="['task-item','task-list']"
  [dragEnterClass]="'drag-enter'"
  [app-draggable]="true"
  [dragTag]="'task-list'"
  [draggedClass]="'drag-start'"
  [dragData]="list"
  (dropped)="handleMove($event,list)"
  [ngStyle]="{'order': list.order}"
  >

2. The list data structure needs to have order, so add the order attribute

lists = [
    {
      id: 1,
      name: "To Do",
      order: 1,
      tasks:
        {
          id: 1,
          desc: "Task 1: Go to Starbucks to buy coffee",
          completed: true,
          priority: 3,
          owner:
            id: 1,
            name: "Zhang San",
            avatar: "avatars:svg-11"
          },
          dueDate: new Date(),
          reminder: new Date()
        },
        {
          id: 2,
          desc: "Task 1: Complete the PPT assignment assigned by the boss",
          completed: false,
          priority: 2,
          owner:
            id: 2,
            name: "Li Si",
            avatar: "avatars:svg-12"
          },
          dueDate: new Date()
        }
      ]
    },
    {
      id: 2,
      name: "In Progress",
      order:2,
      tasks:
        {
          id: 1,
          desc: "Task 3: Project Code Review",
          completed: false,
          priority: 1,
          owner:
            id: 1,
            name: "Wang Wu",
            avatar: "avatars:svg-13"
          },
          dueDate: new Date()
        },
        {
          id: 2,
          desc: "Task 1: Develop a project plan",
          completed: false,
          priority: 2,
          owner:
            id: 2,
            name: "Li Si",
            avatar: "avatars:svg-12"
          },
          dueDate: new Date()
        }
      ]
    }
  ];

3. Change the order when dragging the list to change the order

Exchange the order of the two srcList and the target list

handleMove(srcData,targetList){
    switch (srcData.tag) {
      case 'task-item':
        console.log('handling item');
        break;
      case 'task-list':
        console.log('handling list');
        const srcList = srcData.data;
        const tempOrder = srcList.order;
        srcList.order = targetList.order;
        targetList.order = tempOrder;
      default:
        break;
    }
  }

The above is a detailed explanation of Angular structural directive modules and styles. For more information about Angular structural directive modules and styles, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of angular2 modules and shared modules
  • Angular multi-module project build process
  • Specific usage of angular2 NgModel module
  • Example of Angular implementing preloading of delayed modules
  • Detailed explanation of lazy loading Angular modules using routing
  • A brief discussion on the lazy loading method of Angular2 modules
  • Detailed explanation of the implementation of shared modules in Angular projects

<<:  MySQL5.7.21 decompressed version installation detailed tutorial diagram

>>:  Detailed explanation of installing jdk1.8 and configuring environment variables in a Linux-like environment

Recommend

CSS achieves the effect of aligning multiple elements at both ends in a box

The arrangement layout of aligning the two ends o...

A brief introduction to bionic design in Internet web design

When it comes to bionic design, many people will t...

CSS perfectly solves the problem of front-end image deformation

I saw an article in Toutiao IT School that CSS pe...

MySQL data insertion efficiency comparison

When inserting data, I found that I had never con...

Problems and solutions of using jsx syntax in React-vscode

Problem Description After installing the plugin E...

Example code of Vue3 encapsulated magnifying glass component

Table of contents Component Infrastructure Purpos...

Detailed explanation of Docker daemon security configuration items

Table of contents 1. Test environment 1.1 Install...

Analyze the selection problem of storing time and date types in MySQL

In general applications, we use timestamp, dateti...

Ideas and codes for implementing waterfall flow layout in uniapp applet

1. Introduction Is it considered rehashing old st...

Web project development VUE mixing and inheritance principle

Table of contents Mixin Mixin Note (duplicate nam...

Solutions to VMware workstation virtual machine compatibility issues

How to solve VMware workstation virtual machine c...

jQuery plugin to achieve seamless carousel

Seamless carousel is a very common effect, and it...