当前位置: 代码网 > it编程>前端脚本>AngularJs > 在Angular中使用NgTemplateOutlet创建可重用组件的流程步骤

在Angular中使用NgTemplateOutlet创建可重用组件的流程步骤

2024年05月15日 AngularJs 我要评论
简介单一职责原则是指应用程序的各个部分应该只有一个目的。遵循这个原则可以使您的 angular 应用程序更容易测试和开发。在 angular 中,使用 ngtemplateoutlet 而不是创建特定

简介

单一职责原则是指应用程序的各个部分应该只有一个目的。遵循这个原则可以使您的 angular 应用程序更容易测试和开发。

在 angular 中,使用 ngtemplateoutlet 而不是创建特定组件,可以使组件在不修改组件本身的情况下轻松修改为各种用例。

在本文中,您将接受一个现有组件并重写它以使用 ngtemplateoutlet

先决条件

要完成本教程,您需要:

  • 本地安装了 node.js,您可以按照《如何安装 node.js 并创建本地开发环境》进行操作。
  • 一些关于设置 angular 项目的熟悉程度。

本教程已使用 node v16.6.2、npm v7.20.6 和 @angular/core v12.2.0 进行验证。

步骤 1 – 构建 cardorlistviewcomponent

考虑 cardorlistviewcomponent,它根据其 mode'card''list' 格式中显示 items

它由一个 card-or-list-view.component.ts 文件组成:

import {
  component,
  input
} from '@angular/core';

@component({
  selector: 'card-or-list-view',
  templateurl: './card-or-list-view.component.html'
})
export class cardorlistviewcomponent {

  @input() items: {
    header: string,
    content: string
  }[] = [];

  @input() mode: string = 'card';

}

以及一个 card-or-list-view.component.html 模板:

<ng-container [ngswitch]="mode">
  <ng-container *ngswitchcase="'card'">
    <div *ngfor="let item of items">
      <h1>{{item.header}}</h1>
      <p>{{item.content}}</p>
    </div>
  </ng-container>
  <ul *ngswitchcase="'list'">
    <li *ngfor="let item of items">
      {{item.header}}: {{item.content}}
    </li>
  </ul>
</ng-container>

这是该组件的使用示例:

import { component } from '@angular/core';

@component({
  template: `
    <card-or-list-view
        [items]="items"
        [mode]="mode">
    </card-or-list-view>
`
})
export class usageexample {
  mode = 'list';
  items = [
    {
      header: 'creating reuseable components with ngtemplateoutlet in angular',
      content: 'the single responsibility principle...'
    } // ... more items
  ];
}

该组件没有单一职责,也不够灵活。它需要跟踪其 mode 并知道如何在 cardlist 视图中显示 items。它只能显示具有 headercontentitems

让我们通过使用模板将组件分解为单独的视图来改变这一点。

步骤 2 – 理解 ng-template 和 ngtemplateoutlet

为了让 cardorlistviewcomponent 能够显示任何类型的 items,我们需要告诉它如何显示它们。我们可以通过给它一个模板来实现这一点,它可以用来生成 items

模板将使用 <ng-template> 和从 templaterefs 创建的 embeddedviewrefsembeddedviewrefs 代表具有自己上下文的 angular 视图,是最小的基本构建块。

angular 提供了一种使用这个从模板生成视图的概念的方法,即使用 ngtemplateoutlet

ngtemplateoutlet 是一个指令,它接受一个 templateref 和上下文,并使用提供的上下文生成一个 embeddedviewref。可以通过 let-{{templatevariablename}}="contextproperty" 属性在模板上访问上下文,以创建模板可以使用的变量。如果未提供上下文属性名称,它将选择 $implicit 属性。

这是一个示例:

import { component } from '@angular/core';

@component({
  template: `
    <ng-container *ngtemplateoutlet="templateref; context: examplecontext"></ng-container>
    <ng-template #templateref let-default let-other="acontextproperty">
      <div>
        $implicit = '{{default}}'
        acontextproperty = '{{other}}'
      </div>
    </ng-template>
`
})
export class ngtemplateoutletexample {
  examplecontext = {
    $implicit: 'default context property when none specified',
    acontextproperty: 'a context property'
  };
}

这是示例的输出:

<div>
  $implicit = 'default context property when none specified'
  acontextproperty = 'a context property'
</div>

defaultother 变量由 let-defaultlet-other="acontextproperty" 属性提供。

步骤3 – 重构 cardorlistviewcomponent

为了使 cardorlistviewcomponent 更加灵活,并允许它显示任何类型的 items,我们将创建两个结构型指令来作为模板。这些模板将分别用于卡片和列表项。

这是 card-item.directive.ts

import { directive } from '@angular/core';

@directive({
  selector: '[carditem]'
})
export class carditemdirective {

  constructor() { }

}

这是 list-item.directive.ts

import { directive } from '@angular/core';

@directive({
  selector: '[listitem]'
})
export class listitemdirective {

  constructor() { }

}

cardorlistviewcomponent 将导入 carditemdirectivelistitemdirective

import {
  component,
  contentchild,
  input,
  templateref 
} from '@angular/core';
import { carditemdirective } from './card-item.directive';
import { listitemdirective } from './list-item.directive';

@component({
  selector: 'card-or-list-view',
  templateurl: './card-or-list-view.component.html'
})
export class cardorlistviewcomponent {

  @input() items: {
    header: string,
    content: string
  }[] = [];

  @input() mode: string = 'card';

  @contentchild(carditemdirective, {read: templateref}) carditemtemplate: any;
  @contentchild(listitemdirective, {read: templateref}) listitemtemplate: any;

}

这段代码将读取我们的结构型指令作为 templaterefs

<ng-container [ngswitch]="mode">
  <ng-container *ngswitchcase="'card'">
    <ng-container *ngfor="let item of items">
      <ng-container *ngtemplateoutlet="carditemtemplate"></ng-container>
    </ng-container>
  </ng-container>
  <ul *ngswitchcase="'list'">
    <li *ngfor="let item of items">
      <ng-container *ngtemplateoutlet="listitemtemplate"></ng-container>
    </li>
  </ul>
</ng-container>

这是该组件的使用示例:

import { component } from '@angular/core';

@component({
  template: `
    <card-or-list-view
        [items]="items"
        [mode]="mode">
      <div *carditem>
        静态卡片模板
      </div>
      <li *listitem>
        静态列表模板
      </li>
    </card-or-list-view>
`
})
export class usageexample {
  mode = 'list';
  items = [
    {
      header: '使用 ngtemplateoutlet 在 angular 中创建可重用组件',
      content: '单一职责原则...'
    } // ... 更多项
  ];
}

通过这些更改,cardorlistviewcomponent 现在可以根据提供的模板以卡片或列表形式显示任何类型的项。目前,模板是静态的。

我们需要做的最后一件事是通过为它们提供上下文来使模板变得动态:

<ng-container [ngswitch]="mode">
  <ng-container *ngswitchcase="'card'">
    <ng-container *ngfor="let item of items">
      <ng-container *ngtemplateoutlet="carditemtemplate; context: {$implicit: item}"></ng-container>
    </ng-container>
  </ng-container>
  <ul *ngswitchcase="'list'">
    <li *ngfor="let item of items">
      <ng-container *ngtemplateoutlet="listitemtemplate; context: {$implicit: item}"></ng-container>
    </li>
  </ul>
</ng-container>

这是该组件的使用示例:

import { component } from '@angular/core';

@component({
  template: `
    <card-or-list-view
        [items]="items"
        [mode]="mode">
      <div *carditem="let item">
        <h1>{{item.header}}</h1>
        <p>{{item.content}}</p>
      </div>
      <li *listitem="let item">
        {{item.header}}: {{item.content}}
      </li>
    </card-or-list-view>
`
})
export class usageexample {
  mode = 'list';
  items = [
    {
      header: '使用 ngtemplateoutlet 在 angular 中创建可重用组件',
      content: '单一职责原则...'
    } // ... 更多项
  ];
}

有趣的是,我们使用了星号前缀和微语法来实现语法糖。这与以下代码是相同的:

<ng-template carditem let-item>
  <div>
    <h1>{{item.header}}</h1>
    <p>{{item.content}}</p>
  </div>
</ng-template>

就是这样!我们拥有了原始功能,但现在可以通过修改模板来显示任何我们想要的内容,而 cardorlistviewcomponent 的责任更少了。我们可以向项上下文中添加更多内容,比如类似于 ngforfirstlast,或者显示完全不同类型的 items

结论

在本文中,您将一个现有的组件重写,以使用 ngtemplateoutlet

如果您想了解更多关于 angular 的内容,请查看我们的 angular 专题页面,了解相关练习和编程项目。

以上就是在angular中使用ngtemplateoutlet创建可重用组件的流程步骤的详细内容,更多关于angular ngtemplateoutlet可重用组件的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com