@memberjunction/ng-link-directives
Version:
MemberJunction: Angular Link Directives for turning an element in an angular app into an email, web, or record link
122 lines • 6.21 kB
JavaScript
import { Directive, Input, HostListener } from '@angular/core';
import { NavigationCancel, NavigationEnd, NavigationError } from '@angular/router';
import { CompositeKey, LogError, LogStatus, Metadata } from '@memberjunction/core';
import { BaseLink } from './ng-base-link';
import * as i0 from "@angular/core";
import * as i1 from "@angular/router";
export class FieldLink extends BaseLink {
el;
renderer;
route;
router;
record; // Input variable to get the entity record
fieldName; // Input variable to get the fieldInfo
replaceText = true; //
_targetEntity = '';
_targetEntityInfo;
_targetRecordID = 0;
constructor(el, renderer, route, router) {
super();
this.el = el;
this.renderer = renderer;
this.route = route;
this.router = router;
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
console.log('NavigationEnd:', event.url);
}
if (event instanceof NavigationError) {
LogError(`NavigationError: ${event.error}`);
}
if (event instanceof NavigationCancel) {
LogError(`NavigationCancel: ${event.reason}`);
}
});
}
get field() {
if (!this.record)
throw new Error('entity not set');
if (!this.fieldName)
throw new Error('fieldName not set');
const field = this.record.Fields.find(f => f.Name === this.fieldName);
if (!field)
throw new Error(`Unable to find field ${this.fieldName} in entity ${this.record.EntityInfo.Name}`);
return field;
}
ngOnInit() {
const relatedEntity = this.field.EntityFieldInfo.RelatedEntity;
if (relatedEntity && relatedEntity.length > 0) {
this._targetEntity = relatedEntity;
this._targetRecordID = this.field.Value;
const md = new Metadata();
this._targetEntityInfo = md.Entities.find(e => e.Name === relatedEntity);
if (!this._targetEntityInfo)
throw new Error('Related entity not found in metadata: ' + relatedEntity);
this.CreateLink(this.el, this.field, this.renderer, '', false);
if (this.replaceText) {
// replace the value of the field with the record name
// first see if we already have the value locally using metadata for RelatedEntityNameFieldMap
if (this.field.EntityFieldInfo.RelatedEntityNameFieldMap &&
this.field.EntityFieldInfo.RelatedEntityNameFieldMap.length > 0) {
const nameField = this.field.EntityFieldInfo.RelatedEntityNameFieldMap;
const nameFieldValue = this.record.Get(nameField);
if (nameFieldValue && nameFieldValue.length > 0)
this.renderer.setProperty(this.el.nativeElement, 'textContent', nameFieldValue);
}
else if (this.field.Value) {
// make sure that this.field.Value is not null or undefined
// we didn't have the related field mapping info (above), no related entity name field map provided in the entity field metadata, so do a lookup
// requires a server round trip and hitting the DB, so we try to avoid this
let compositeKey = new CompositeKey([{
FieldName: this._targetEntityInfo.FirstPrimaryKey.Name, // AT THE MOMENT - we only support foreign keys with a single value
Value: this.field.Value
}]);
md.GetEntityRecordName(relatedEntity, compositeKey).then(recordName => {
if (recordName && recordName.length > 0)
this.renderer.setProperty(this.el.nativeElement, 'textContent', recordName);
});
}
}
}
else {
LogStatus('no linked entity found for field: ' + this.field.Name);
}
}
onClick(event) {
event.preventDefault();
if (!this._targetEntityInfo)
throw new Error('targetEntityInfo not set');
// AT THE MOMENT - we only support foreign keys with a single value
const keyVals = `${this._targetEntityInfo.FirstPrimaryKey.Name}|${this._targetRecordID}`;
const newURL = ['resource', 'record', keyVals];
this.router.navigate(newURL, { queryParams: { Entity: this._targetEntity } }).then(params => {
console.log('navigated to:', newURL.join('/'));
}).catch(err => {
const newURLString = newURL.join('/');
LogError(`Error navigating to ${newURLString}: ${err}`);
});
}
static ɵfac = function FieldLink_Factory(t) { return new (t || FieldLink)(i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(i0.Renderer2), i0.ɵɵdirectiveInject(i1.ActivatedRoute), i0.ɵɵdirectiveInject(i1.Router)); };
static ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective({ type: FieldLink, selectors: [["", "mjFieldLink", ""]], hostBindings: function FieldLink_HostBindings(rf, ctx) { if (rf & 1) {
i0.ɵɵlistener("click", function FieldLink_click_HostBindingHandler($event) { return ctx.onClick($event); });
} }, inputs: { record: "record", fieldName: "fieldName", replaceText: "replaceText" }, features: [i0.ɵɵInheritDefinitionFeature] });
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(FieldLink, [{
type: Directive,
args: [{
selector: '[mjFieldLink]'
}]
}], () => [{ type: i0.ElementRef }, { type: i0.Renderer2 }, { type: i1.ActivatedRoute }, { type: i1.Router }], { record: [{
type: Input,
args: ['record']
}], fieldName: [{
type: Input,
args: ['fieldName']
}], replaceText: [{
type: Input,
args: ['replaceText']
}], onClick: [{
type: HostListener,
args: ['click', ['$event']]
}] }); })();
//# sourceMappingURL=ng-field-link.js.map