Explain the instruction module and style of angular structure in detail

Time:2021-7-29
catalogue
  • 1、 Structured instruction
  • Two, module Module
    • Write a forroot ()
  • 3、 Style definition
    • Use ngstyle to adjust the order when dragging

1、 Structured instruction

*Is a syntax sugar, < A * ngif = “user. Login” > Exit < / 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 structured instructions change structures?

Ngif source code

The set method is marked as @ input. If the condition is true and does not contain a view, set the internal hasview ID position to true, and then create a child view according to the template through the viewcontainer.

If the condition is not true, empty the contents with the view container.

Viewcontainerref: container, the container of the view in which the instruction is located

Two, module Module

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

Module metadata

Entrycomponents: the module should be loaded immediately (such as a dialog box), rather than when it is called.

Exports: if you want the internal of the module to be shared by everyone, you must export it.

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>;
}

Metadata changes according to different situations. Metadata cannot be specified dynamically. Instead of writing metadata, a static engineering method is directly constructed and a module is returned.

Write a forroot ()

Create a servicemodule: $ng g m services


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

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

No metadata in servicemodule. Use a static method forroot to return.


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

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

Used when importing in the core module

imports: [ServicesModule.forRoot();]

3、 Style definition

Ngclass, ngstyle, and [class. Yourclass]

Ngclass: used to specify the style class conditionally and dynamically. It is suitable for making a large number of changes to the style. Predefined class.


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

Ngstyle: used to specify the style conditionally and dynamically, which is suitable for small changes. For example, [ngstyle] = “{‘order’: list. Order}” in the following example. Key is a string.

[class. Yourclass]: [class. Yourclass] = “condition” directly corresponds to a condition. This condition is suitable for the application of this class. Equivalent to ngclass, equivalent to a variant of ngclass, abbreviated.


<div 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 order is sorted according to order.


<app-task-list *ngFor="let list of lists" 
 
  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. Order is required in the list data structure, so the order attribute is added

lists = [
    {
      id: 1,
      "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 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: make project plan",
          completed: false,
          priority: 2,
          owner: {
            id: 2,
            Name: "Li Si",
            avatar: "avatars:svg-12"
          },
          dueDate: new Date()
        }
      ]
    }
  ];

3. When dragging the list to change the order, change the order

Exchange the order of two srclists 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 the detailed explanation of angular structured instruction modules and styles. For more information about angular structured instruction modules and styles, please pay attention to other relevant articles of developeppaer!