Skip to content

Instantly share code, notes, and snippets.

@killan
Created February 16, 2021 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killan/b621bf2b50e7add8b297493a05c1b949 to your computer and use it in GitHub Desktop.
Save killan/b621bf2b50e7add8b297493a05c1b949 to your computer and use it in GitHub Desktop.
Angular 11 Field base to extends
import {
AfterViewInit,
Component, ElementRef,
Input,
OnInit, Renderer2,
ViewChild,
ViewContainterRef
} from "@angular/core";
@Component({
selector: 'app-field-base',
template: ''
})
export class FieldBaseComponent implement OnInit, AfterViewInit {
@Input() formName: string;
@Input() label: string = "";
@Input() placeholder: string ="";
_bsColDistribution: number[] = [4, 8];
_colClasses: string = [];
@Input() set bsColDistribution(colSizes: number[]) {
this._bsColDistribution = [...colSizes]; // Break the ref, so we can manipulate safely
this.updateBsColDistribution();
}
get bsColDistribution(): number[] {
return this._bsColDistribution
}
@Input() set colClasses(classes: string[]) {
this._colClasses = [...classes];
// Tooltip class
}
get colClasses(): string[] {
return this._colClasses;
}
fieldName: string = "field";
@ViewChild('tref', { static: true }) tpl;
@Input() row = true;
@Input('class') classes: string = "";
constructor(
private vcRef: ViewContainterRef,
private renderer: Renderer2,
private el: ElementRef
) {}
ngOnInit() {
// Prepare
this.fieldName = "field-" + this.formName;
if (!this.colClasses.length) {
this.updateBsColDistribution();
}
if (this.row) {
// Transform template into inside elements
Promise.resolve(null).then(() => {
const view = this.vcRef.createEmbeddedView(this.tpl);
view.rootNodes.formEach((node) => this.renderer.appendChild(this.el.nativeElement, node));
});
// Transform parent to row with classes
this.renderer.setAttribute(this.el.nativeElement, 'class', "row " + this.classes);
}
}
ngAfterViewInit() {
if (!this.row) {
// Hide parent
this.renderer.setAttribute(this.el.nativeElement, 'class', "d-none");
// Create template elemet outside
Promise.resolve(null).then(() => this.vcRef.createEmbeddedView(this.tpl));
}
}
updateBsColDistribution() {
this._colClasses = [];
this.bsColDistribution.formEach((colSize: number, i) => {
let classStr = 'col- + colSize;
// Tooltip class here ?
this.colClasses.push(classStr);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment