未加星标

Creating a Reusable Accordion Component That Works Anywhere

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

Creating a Reusable Accordion Component That Works Anywhere
The final web component

Web Components is the hottest trend in web development and it’s only going to gain momentum since most of the major browsers now support them. Web components are custom made tags which extend HTML’s capabilities. This is not only good for code reusability but also if you are making a shift from one framework to another or want to use a component which is already implemented in some other framework.

Although there are a number of good web components compilers like Stencil and Polymer , this tutorial will mainly focus on using Angular Elements and how to use it to make a collapsible accordion web component.


Creating a Reusable Accordion Component That Works Anywhere

Components previously make using Angular Elements could only be used with Angular but with the recent release, it can now be used as a true web component. By ‘true web component’, I mean the one which adheres to the specifications.

Web components are based on four main specifications:

Custom Elements : For designing and using new DOM elements. Shadow DOM : To Encapsulate styles and markup. i.e. Prevent conflict between the styles of the components and the other html elements. ES Modules : Specifies how to include and reuse JS files so that the project stays modular and performs well. HTML Template : Specifies how to declare fragments of markup that go unused at page load, but can be instantiated later on at runtime.

Tip: Build faster by making components reusable with Bit. Share a collection as a team, discover your components and use them to build faster together. Give it a try.

Bit - Share and build with code components

Bit helps you share, discover and use code components between projects and applications to build new features and… bitsrc.io

Steps to make a web component

I am using angular/cli version 7.1.4. To check your version use ng -v or ng version command in your terminal.

I tried to use the shiny new Ivy compiler, but it has some bugs and for some reason, the package size was larger than the one that the current angular compiler builds. In future releases of Angular, Ivy should be the default and hence I hope that the following steps won’t change.

Step 1: Setup a new angular project using the angularcli.

ng new accordion --prefix custom --routing=false

Open the project in your preferred editor or file manager and delete all the files in app folder except the app.module file.


Creating a Reusable Accordion Component That Works Anywhere
Delete the selectedfiles.

ng g component accordion --inline-template -v ShadowDom

The above command will generate a new component with ViewEncapsulation as ShadowDom. This allows creating separate DOM trees which are isolated from the main DOM tree and it also supports ‘slots’.

CSS and markup will stay confined to your component and won’t leak or conflict with the other components of the website. Add the angular/elements package. On the other hand, it becomes difficult to change the styles of the component.

Next, we will add the angular elements package to our project.

ng add @angular/elements

Step 2: Configure app.module.ts and prepare for elements.

In the @NgModule decorator, remove the bootstrap property and add the entryComponents array with your custom components.

@NgModule({ declarations: [ AccordionComponent ], imports: [ BrowserModule ], providers: [], entryComponents: [AccordionComponent] })

Below that we will have to define some configs related to our components and register each component that the final package will include.

export class AppModule {
constructor(injector: Injector) {
const acc = createCustomElement(AccordionComponent, { injector });
customElements.define('custom-accordion',acc);
} ngDoBootStrap() {} }

In tsconfig.json find the “target” property and change ‘es5’ to ‘es2015’.

{
...
“target”: “es2015”,
...
} Step3: Add the HTMLmarkup.

We are using an inline template since it is a small template.

@Component({ ... template: ` <button #el class="accordion" (click)="toggleHelper()"> <slot name="header">Default header</slot> </button> <div class="panel"> <slot name="details">Default details</slot> </div>`, ... })

A side note on slots

Slots can be used when you want content to be placed in specific locations in your template. There are two types of slots, default and named. We are using the named slot here.

Default Slotcan be use if the user of the component will have only one place to put his markup.

<!--Component HTML --> <img src=”…”> <slot></slot>

Now HTML can be included inside the component and will be rendered below the image.

<!--Usage --> <my-component> <h1>Image Caption</h1> </my-component>

Named Slotsallow you to give reference names to different slots and hence more than one slot can be used. In your component, you need to add the name attribute as shown.

<!-- Component HTML --> <h1><slot name=”header”>Default Header</slot></h1> <p><slot name=”caption”>Default Caption</slot></p>

Now the end user of the web component can just pass a span that references the slot name and it will be rendered in the matching location.

<! ― Usage → <my-element> <span slot=”caption”>Some cool caption</span> <span slot=”header”>My Custom Header</span> </my-element> Step 4: Add thestyles

This is just personal preferences and your CSS skills.

Step 5: Add the toggle logic in the typescript file

On the 2nd line we have an @Input() icon property which is not required for this example but if you want to add more features this is an important concept to know. This icon property will be available as an attribute for your web component. You can use it as

<custom-accordion icon='plus'></custom-accordion>

// accordion.component.ts export class AccordionComponent {
@Input() icon = 'ar

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Creating a Reusable Accordion Component That Works Anywhere
本站链接:https://www.codesec.net/view/628313.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(72)