首页 > 语言 > JavaScript > 正文

Angular7中创建组件/自定义指令/管道的方法实例详解

2024-05-06 15:41:11
字体:
来源:转载
供稿:网友

组件

使用命令创建组件

•创建组件的命令:ng generate component 组件名
•生成的组件组成: 组件名.html 、组件名.ts、组件名.less、组件名.spec.ts
•在组件的控制器

@Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.less']})

手动创建组件

1.创建一个组件ts文件

2.在组件中设置

// 1. 导入包,按需导入import { Component } from "@angular/core";import { CoreEdit, NavLayoutComponent } from "@reco/core";import { DinerService } from "../Service";// 2.定义当前组件的修饰器@Component({ // 支出对外使用的名称 selector: "diner-birth", // 使用的模板 templateUrl: "./diner.birth.html"})// 导出使用的类export class DinerBirthComponent extends CoreEdit { constructor( private _dinerService: DinerService, layout: NavLayoutComponent ) { super(_dinerService, 'diner-birth', layout); }}

1.在index.ts文件中引入并导出

// 1. 导入import { DinerBirthComponent } from "./diner.birth";// 2. 导出export { DinerBirthComponent }// 3. 注册@NgModule({ // 这里列出的 NgModule 所导出的可声明对象可用在当前模块内的模板中 imports: [....], // declarations:[ 组件 ] 属于该模块的一组组件、指令和管道(统称可声明对象)。 // 注意点:在这个源数据中只能声明组件、管道、指令 declarations: [DinerBirthComponent], // 定义此 NgModule 中要编译的组件集,这样它们才可以动态加载到视图中。 entryComponents: [....], // 导出的模块 exports: [....]})

指令

认识指令

•说明:在 Angular 中有三种类型的指令: ◦1.组件 — 拥有模板的指令
◦2.结构型指令 — 通过添加和移除 DOM 元素改变 DOM 布局的指令
◦3.属性型指令 — 改变元素、组件或其它指令的外观和行为的指令。

自定义指令

•创建自定义指令的命令: ng g d 目录/指令名称

•创建指令

1.创建指令的文件ts文件

2.在指令文件中写

import { Directive, ElementRef, Input, Output } from '@angular/core';// 自定义指令@Directive({ selector: '[dinerHidden]'})// 导出指令的模块export class DinerHiddenDirective { // el 代表当前的元素 constructor(el: ElementRef) { // console.log() el.nativeElement.style.display = "none" }}1.在index.ts中将该指令导入到ngModule中// 1.导入import { DinerHiddenDirective } from "./diner.hidden";// 2.导出export const DINER_COMPONENTS: Provider[] = [ DinerHiddenDirective ];// 3.ngModule中注册@NgModule({ // 这里列出的 NgModule 所导出的可声明对象可用在当前模块内的模板中 imports: [], // declarations:[ 组件 ] 属于该模块的一组组件、指令和管道(统称可声明对象)。 // 注意点:在这个源数据中只能声明组件、管道、指令 declarations: [DINER_COMPONENTS], // 定义此 NgModule 中要编译的组件集,这样它们才可以动态加载到视图中。 entryComponents: []})            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选