详解创建自定义的Angular Schematics(2)

import { Component, Input, } from '@angular/core'; @Component({ selector: 'my-first-schema-component', templateUrl: './my-first-schema.component.html', styleUrls: [ './my-first-schema.component.css' ] }) export class MyFirstSchemaComponent { constructor(){ console.log( '<%= classify(name) %>' ); } }

这是一个模板文件,其中可以看到 <%= classify(name) %> 的内容。当你在使用这个 schematics 的时候,classify 将用来获取 options 中的 name 的值。

my-first-schema.component.html

<% if (service) { %> <h1>Hola Service</h1> <% } %> <% if (!service) { %> <h1>Hola no Service</h1> <% } %>

这里的 service 同样来自 options,我们定义了一个 Boolean 类型的选项。

my-first-schema.component.css,这个文件目前保持为空即可。

回到控制台,在你的项目文件夹中执行 build 命令:npm run build

定义已经完成。

3. 在 Angular 项目中使用这个 Schematics

下面,我们在其它文件夹中,创建一个新的 Angular 项目,以便使用刚刚创建的这个 Schematics。

ng new test-schematics

进入到这个项目中,使用我们新创建的 schematics。

在其 node-modules 文件夹中创建名为 mfs 的模块文件夹,我们还没有将新创建的 Schematics 上传到 Npm 中,这里我们手工将其复制到新建的 Angular 项目中。

将您前面创建的 schematics 项目中所有的文件(除了 node_modules 文件夹和 package-lock.json 文件之外),复制到这个 mfs 文件夹中,以便使用。

现在,我们可以使用前面创建的这个 schematics 了。

ng g my-first-schema mfs  — service  — name=”Mfs”  — collection mfs

这里设置了 name 和 service 的值。

你应该看到如下的输出:

PS test-schematics> ng g my-first-schema mfs --service --name="Mfs" --collection mfs
  create src/app/my-schema/my-first-schema.component.css (0 bytes)
  create src/app/my-schema/my-first-schema.component.html (33 bytes)
  create src/app/my-schema/my-first-schema.component.ts (320 bytes)
PS test-schematics>

在刚才新建的 Angular 项目 src/app 文件夹中,已经新建了一个名为 my-first-schema 的文件夹,其中包含了三个文件。

打开 my-first-schema.component.ts 文件,可以看到替换之后的内容

import { Component, Input, } from '@angular/core'; @Component({ selector: 'my-first-schema-component', templateUrl: './my-first-schema.component.html', styleUrls: [ './my-first-schema.component.css' ] }) export class MyFirstSchemaComponent { constructor(){ console.log( 'Mfs' ); } }

而在 my-first-schema.component.html 中,可以看到 --service 的影响。

<h1>Hola Service</h1>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1ddbb728167875de0f3c054b1361a64e.html