Polymer 3.0 dom-repeat not repeating template - polymer-3.x

Hi I was working on a todo list app with Polymer 3.0 and am having some trouble getting dom-repeat to work.
Here is the code I have:
/** #format */
import { html, PolymerElement } from '#polymer/polymer/polymer-element.js';
import '#polymer/paper-button/paper-button.js';
import '#polymer/paper-checkbox/paper-checkbox.js';
import '#polymer/paper-input/paper-input.js';
import '#polymer/polymer/lib/elements/dom-repeat.js';
/**
* `todo-element`
*
*
* #customElement
* #polymer
* #demo demo/index.html
*/
class TodoElement extends PolymerElement {
static get template() {
return html`
<style>
:host {
display: block;
}
</style>
<h2>[[name]]</h2>
<div class="todo-list>
<dom-repeat items={{tasks}}>
<template>
<div class="task">
<paper-checkbox></paper-checkbox>
<paper-input label="Task: " value="[[task]]"></paper-input>
</div>
</template>
</dom-repeat>
<paper-button>Add Task</paper-button>
<h4>[[sub]]</h4>
</div>
`;
}
static get properties() {
return {
name: {
type: String,
value: 'Todo list',
},
sub: {
type: String,
value: 'Completed',
},
tasks: {
type: Array,
value: () => ['task1', 'task2', 'task3'],
},
};
}
}
window.customElements.define('todo-element', TodoElement);
Here what I see on the webapp:
What I am expecting is to see 3 of the checkbox, input, and button but I only get one. Thanks in advance for any assistance on this!

I was missing a " in my <div class="todo-list>. When I switched it to it started working

Related

Styles are not being picked up in my Lit component

I'm trying to implement a Lit component with some scss styling. Below is the component as it is right now:
import { html, LitElement } from 'lit-element';
import { ScopedElementsMixin } from '#open-wc/scoped-elements';
// Components
import 'inputmessage';
// Styles
import styles from './input-styles.scss';
export default class Input extends ScopedElementsMixin(LitElement) {
constructor() {
super();
}
static get properties() {
return {
label: { type: String, attribute: 'label' },
id: { type: String, attribute: 'id' },
value: { type: String, attribute: 'value' },
statusMessage: { type: String, attribute: 'status-message' },
statusType: { type: String, attribute: 'status-type' },
required: { type: Boolean, attribute: 'required' },
placeholder: { type: String, attribute: 'placeholder' },
type: { type: String, attribute: 'type' },
};
}
static get scopedElements() {
return {
'inputmessage': customElements.get('inputmessage'),
};
}
static get styles() {
return [styles];
}
render() {
return html`
<div>
${this.label && html`<label class="input-label" for="${this.id}">${this.label}</label>`}
<input type="${this.type}" required="${this.required}" value="${this.value}" placeholder="${this.placeholder}" id="${this.id}" name="${this.id}" />
</div>
`;
}
}
The CSS styles are in scss and only include the .input-label class. Now when I try to render the component on the screen it doesn't appear and I see the following message in the console output:
It seems the styles are not being picked up for some reason. I added the lit-scss-loader in my dependencies, but that also doesn't work. Anyone knows what I should do?
You need to use css tagged template function and unsafeCSS(str) function to make use of CSS imported into a string:
import { html, LitElement, css, unsafeCSS } from 'lit-element';
// later, inside your component class:
static get styles() {
return css`${unsafeCSS(styles)}`;
}
I have no clue what translates your SCSS, stopped using pre-processors years ago.
I can't comment so write new answer.
Lit don't process SCSS file.
If you need library check this library.
lit-scss-loader
other solution:
Convert scss to css manually then use this code.
import styles from './my-styles.css' assert { type: 'css' };
class MyEl extends LitElement {
static styles = [styles];
}
Note : above solution only work with chromium based browser.
Wait for other browser support.

Ag-grid gridReady event not working in storybook

I'm facing a issue with AG-grid in Storybook.
I'm trying to do filtration in AG-grid added as storybook template. But gridReady event doesn't get fired
Here is the code for reference
someApp.component.html
<div style="float: right; width: 100%;display: flex; <=== this is dive to have search field. We can add input here.
flex-direction: row;
justify-content: flex-end;">
<mat-search-bar (keyup)="applyFilter($event.target.value)" (onClose)="clearFilter()" [placeholder]="Search"></mat-search-bar>
</div> <===== on keyup it takes the input from search field and get the filter data in AG-Grid
</mat-toolbar>
<div class=" ag-grid-container">
<ag-grid-angular
class="ag-theme-material ag-grid-container"
[columnDefs]="columnDefs"
[rowData]="rowdef"
[suppressColumnMoveAnimation]="true"
[suppressDragLeaveHidesColumns]="true"
[overlayNoRowsTemplate]="overlayNoRowsTemplate"
(gridReady)="onGridReady($event)"
>
</ag-grid-angular>
In the above code, I get the value of search and call applyFilter to set quickfilter in grid
someApp.component.ts
columnDefs = [
{ headerName:'Sports', field: 'sports'},
{ headerName:'No: of Players', field:'player'},
];
gridApi!: GridApi;
Search = "Search";
onGridReady (params) {
console.log('calling grid Api');
this.gridApi = params.api;
console.log('called grid Api: '+this.gridApi);
}
ngOnInit() {
}
public overlayNoRowsTemplate =
'<div *ngIf="rowDef.length === 0" class="no-records">No database found.</div>';
applyFilter(value: string) {
console.log(value);
this.gridApi.setQuickFilter(
value
);
}
clearFilter() {
this.gridApi.setQuickFilter(""
);
}
someApp.stories.ts
import {
GridApi,
GridReadyEvent,
ICellRendererParams
} from 'ag-grid-community';
import { moduleMetadata, Meta } from '#storybook/angular';
import { ActionsComponent } from 'projects/web-component-library/src/lib/components/actions/app-actions.component';
import {someApp} from '../../projects/web-component-library/src/lib/components/inventory/inventory.component';
import { MaterialModule } from '../../projects/web-component-library/src/lib/components/material';
import { BrowserAnimationsModule, NoopAnimationsModule } from '#angular/platform-browser/animations';
import { NgMatSearchBarModule } from 'ng-mat-search-bar';
import { AgGridModule } from 'ag-grid-angular';
import { RouterModule } from '#angular/router';
import { CustomActionComponent } from 'projects/web-component-library/src/lib/components/custom-action/custom-action.component';
const rowdef = [{sports:'Cricket', player:11},
{sports:'Basketball', player:5}
]
export default {
title: 'Data Inventory',
component: someApp,
decorators: [
moduleMetadata({
declarations: [someApp,CustomActionComponent],
imports: [MaterialModule, BrowserAnimationsModule, NoopAnimationsModule,NgMatSearchBarModule,AgGridModule.withComponents([CustomActionComponent]),RouterModule]
}),
],
} as Meta;
export const Default = (args: someApp) => ({
component: someApp,
props: args
});
Default.args = {
rowdef
};
export const NoData = (args: someApp) => ({
component: someApp,
props: args
});
NoData.args = {
rowdef:[]
};
When I try to search something
it gives error as this.gridApi is undefined. whereas when I add this in parent HTML as below and run as 'ng serve', its works fine
App.component.html
<some-app><some-app>
Seems like onGridReady is not fired properly in storybook.
Using
Storybook 6.0.12
Angular 8
npm 6.13.4
node v10.19.0
Log of error in storybook

How can I toggle a class in a LitElement Web Component

I am working with precompiled stylesheet (from SASS) and only need to toggle classes.
I have two elements that will be writing to an event. Based on the event being true/false I want to to toggle a class on my component.
Would this work:
import { LitElement, html } from 'lit-element'
/**
*
*
* #export
* #class MenuMainButton
* #extends {LitElement}
*/
export class MenuMainButton extends LitElement {
static get properties() {
return {
name: { type: String },
toggled: { type: String }
}
}
constructor() {
super()
this.name = 'Menu'
this.toggled = ''
this.addEventListener('toggle-main-menu', this.handleEvents)
}
render() {
return html`
<a #click=${this._onClick} class="menu-button wk-app-menu-button app-menu-open ${this.toggled} govuk-body"
>${this.name}</a
>
`
}
handleEvents(event) {
this.toggled = event.toggle ? 'hide-item' : ''
}
_onClick() {
const toggleMainMenu = new CustomEvent('toggle-main-menu', {
toggle: this.toggled === '' ? 1 : 0
})
this.dispatchEvent(toggleMainMenu)
}
}
window.customElements.define('main-menu-button', MenuMainButton)
One way to make styles dynamic is to add bindings to the class or style attributes in your template.
The lit-html library offers two directives, classMap and styleMap, to conveniently apply classes and styles in HTML templates.
Styles - LitElement

shadowRoot.activeElement is not working in safari

Currently I am working on stencilJS which has feature to implement shadow dom. I am facing an issue related to activeElement of the shadowRoot.It is working fine with Chrome but when I am testing my component then activeElement is getting null in safari.
Here is the code snippet
import { Component, Prop, Listen } from '#stencil/core';
#Component({
tag: 'my-component',
styleUrl: 'my-component.css',
shadow: true
})
export class MyComponent {
/**
* The first name
*/
#Prop() first: string;
/**
* The middle name
*/
#Prop() middle: string;
/**
* The last name
*/
#Prop() last: string;
#Listen('click')
onHadnleClickEvent(ev) {
console.log('===== 31 =====', ev.target.shadowRoot.activeElement)// getting null in safari
}
render() {
return ( <div>
<button>Click Me!!!</button>
</div>
)
}
}
I found the result to get the clicked element when shadowDom is enabled. Here is the solution:
#Listen('click')
onHadnleClickEvent(ev) {
console.log('===== 31 =====', ev.composedPath()[0]// It will give you the clicked element
}

Using proper CSS media queries in Angular

I read that in Angular it is a very bad practice to use the CSS hidden element to hide an element like this:
.container{
background-color : powderblue;
height : 50px;
width : 100%
}
#media (max-width: 400px){
.container{
display: none;
}
}
<div class="container"></div>
And I know the Angular way to show or hide an element is using the *ngIf directive.
Question
How can I get the * ngIf to react on the media query in an 'Angular fashion'?
You can use angular/breakpoints-angular-cdk
follow these steps
on the terminal
npm install #angular/cdk
Then import the layout module and and add it to your NgModule’s list of imports
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { LayoutModule } from '#angular/cdk/layout';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
LayoutModule
],
providers: [],
bootstrap: [AppComponent]
})
right after you can use it in your component, just import these classes from #angular/cdk/layout
import { Component, OnInit } from '#angular/core';
import { BreakpointObserver, BreakpointState } from '#angular/cdk/layout';
#Component({ ... })
export class AppComponent implements OnInit {
public showContainer: boolean;
constructor(public breakpointObserver: BreakpointObserver) {}
ngOnInit() {
this.breakpointObserver
.observe(['(min-width: 400px)'])
.subscribe((state: BreakpointState) => {
if (state.matches) {
this.showContainer = true;
} else {
this.showContainer = false;
}
});
}
}
Check the docs it is a simple API
Angular flex layout is better solution for this. You wouldn't need media queries and it has special responsive feature to show and hide for example
fxShow: This markup specifies if its host element should be displayed (or not)
<div fxShow [fxShow.xs]="isVisibleOnMobile()"></div>
fxHide: This markup specifies if its host element should NOT be displayed
<div fxHide [fxHide.gt-sm]="isVisibleOnDesktop()"></div>
No need to write lot of css and it's very compatible with angular material.
https://github.com/angular/flex-layout
I came up with the following base class and have found it works well.
import { HostBinding, OnDestroy, OnInit } from '#angular/core';
import { MediaObserver } from '#angular/flex-layout';
import { Subscription } from 'rxjs';
export class MediaQueryClassBaseComponent implements OnInit, OnDestroy {
#HostBinding('class.xl') private xl: boolean;
#HostBinding('class.lg') private lg: boolean;
#HostBinding('class.md') private md: boolean;
#HostBinding('class.sm') private sm: boolean;
#HostBinding('class.xs') private xs: boolean;
private mediaObserverSubscription: Subscription | undefined = undefined;
constructor(protected readonly mediaObserver: MediaObserver) {}
ngOnInit(): void {
if (this.mediaObserverSubscription)
return;
this.mediaObserverSubscription = this.mediaObserver.media$.subscribe(x => {
this.xl = x.mqAlias == 'xl';
this.lg = x.mqAlias == 'lg';
this.md = x.mqAlias == 'md';
this.sm = x.mqAlias == 'sm';
this.xs = x.mqAlias == 'xs';
});
}
ngOnDestroy(): void {
if (!this.mediaObserverSubscription)
return;
this.mediaObserverSubscription.unsubscribe();
this.mediaObserverSubscription = undefined;
}
}
If you inherit (extend) your component from this class, the host element of your component will have a class added to it with the media query alias.
For example...
<app-search-bar class="some-class" _nghost-c5 ...>
...will become...
<app-search-bar class="some-class lg" _nghost-c5 ...>
Note the added media query alias 'lg' which will change according to the window size. This makes it easy to add responsive styles to each media size by
wrapping the size-specific styles in your component's SCSS files.
Like this...
:host-context(.sm, .md) { // styles specific to both sm and md media sizes
.header {
padding: 6px;
width: 420px;
}
}
:host-context(.lg, .xl) { // styles specific to both lg and xl media sizes
.header {
padding: 10px;
width: 640px;
}
}
I've put the full file on my gist https://gist.github.com/NickStrupat/b80bda11daeea06a1a67d2d9c41d4993
Check here, it's forked solution found somewhere on internet with my customization, but it works for me (not only hiding element with display:none, but removing if from DOM - like *ngIf works)
import {
Input,
Directive,
TemplateRef,
ViewContainerRef,
OnDestroy,
ChangeDetectorRef
} from '#angular/core';
/**
* How to use this directive?
*
* ```
*
* Div element will exist only when media query matches, and created/destroyed when the viewport size changes.
*
* ```
*/
#Directive({
selector: '[mqIf]'
})
export class MqIfDirective implements OnDestroy {
private prevCondition: boolean = null;
i = 0;
private mql: MediaQueryList;
private mqlListener: (mql: MediaQueryList) => void; // reference kept for cleaning up in ngOnDestroy()
constructor(private viewContainer: ViewContainerRef,
private templateRef: TemplateRef,
private ref: ChangeDetectorRef) {
}
/**
* Called whenever the media query input value changes.
*/
#Input()
set mqIf(newMediaQuery: string) {
if (!this.mql) {
this.mql = window.matchMedia(newMediaQuery);
/* Register for future events */
this.mqlListener = (mq) => {
this.onMediaMatchChange(mq.matches);
};
this.mql.addListener(this.mqlListener);
}
this.onMediaMatchChange(this.mql.matches);
}
ngOnDestroy() {
this.mql.removeListener(this.mqlListener);
this.mql = this.mqlListener = null;
}
private onMediaMatchChange(matches: boolean) {
if (matches && !this.prevCondition) {
this.prevCondition = true;
this.viewContainer.createEmbeddedView(this.templateRef);
} else if (!matches && this.prevCondition) {
this.prevCondition = false;
this.viewContainer.clear();
}
/**
* Infinitive loop when we fire detectChanges during initialization
* (first run on that func)
*/
if (this.i > 0) {
this.ref.detectChanges();
}
else
this.i++;
}
}
See here
.container{
background-color : powderblue;
height : 50px;
width : 100%
}
#media (max-width: 400px){
.container{
display: flex;
}
}
<div class="container"></div>

Resources