### File

`projects/app-base-library/src/lib/angular/components/svg-template.component.ts`

### Implements

`OnChanges`

### Metadata

providers | `ReplaceAllPipe` `BetweenPipe`
selector | `svg-template`

template

    <div *ngIf="_svg" [innerHTML]="trustAsHtml(_svg)" class="svg-container embedded"></div>

### Index

###### Properties

- Private _containerElements
- Private _dataCurrent
- Private _dataNew
- Private _src
- Public _svg
- Private _svgElement
- Public el
- Public elementRef
- Private settings
- Public type

###### Methods

- centerSketchUIText
- initSvg
- loadSvg
- ngOnChanges
- ngOnInit
- prepareLoadedSvg
- renderData
- renderSvg
- renderTemplateData
- svgCalculateSize
- trustAsHtml

###### Inputs

- data
- src

###### Outputs

- loaded

### Constructor

`constructor(baseService: BaseService, elementRef: ElementRef, http: Http, renderer: Renderer, _sanitizer: DomSanitizer, replaceAll: ReplaceAllPipe, betweenPipe: BetweenPipe)`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:28

Parameters :

Name | Type | Optional
baseService | `BaseService` | no
elementRef | `ElementRef` | no
http | `Http` | no
renderer | `Renderer` | no
_sanitizer | `DomSanitizer` | no
replaceAll | `ReplaceAllPipe` | no
betweenPipe | `BetweenPipe` | no

### Inputs

`data` | Type: `any` Default value: `{}`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:17

`src` | Type: `string`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:16

### Outputs

`loaded` | `$event` type: `EventEmitter<any>`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:18

### Methods

centerSketchUIText
`centerSketchUIText()`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:228
Returns : `void`

initSvg
`initSvg(svgElement: )`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:65

Parameters :

Name | Optional
svgElement | no

Returns : `void`

loadSvg
`loadSvg()`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:213
Returns : `void`

ngOnChanges
`ngOnChanges(changes: )`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:42

Parameters :

Name | Optional
changes | no

Returns : `void`

ngOnInit
`ngOnInit()`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:34
Returns : `void`

prepareLoadedSvg
`prepareLoadedSvg(svgResult: string)`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:174

Parameters :

Name | Type | Optional
svgResult | `string` | no

Returns : `void`

renderData
`renderData()`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:96
Returns : `void`

renderSvg
`renderSvg()`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:107
Returns : `void`

renderTemplateData
`renderTemplateData()`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:69
Returns : `void`

svgCalculateSize
`svgCalculateSize(svg: )`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:333

Parameters :

Name | Optional
svg | no

Returns : `{ width: any; height: any; }`

trustAsHtml
`trustAsHtml(content: )`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:362

Parameters :

Name | Optional
content | no

Returns : `any`

### Properties

Private _containerElements
`_containerElements: `any``
Type : `any`
Default value : `{}`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:25

Private _dataCurrent
`_dataCurrent: `any``
Type : `any`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:23

Private _dataNew
`_dataNew: `any``
Type : `any`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:24

Private _src
`_src: `string``
Type : `string`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:26

Public _svg
`_svg: `any``
Type : `any`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:21

Private _svgElement
`_svgElement: `any``
Type : `any`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:22

Public el
`el: `HTMLElement``
Type : `HTMLElement`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:27

Public elementRef
`elementRef: `ElementRef``
Type : `ElementRef`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:30

Private settings
`settings: ```
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:20

Public type
`type: `string``
Type : `string`
Defined in projects/app-base-library/src/lib/angular/components/svg-template.component.ts:28

    import { Component, ElementRef, EventEmitter, Renderer, Input, Output, OnChanges } from '@angular/core';
    import { Http, Response } from '@angular/http';
    import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
    import { BetweenPipe, ReplaceAllPipe } from '../pipes/index';
    import { BaseService } from '../services/base.service';
    declare var _: any;
    declare var $: any;

    @Component({
        selector: 'svg-template',
        template: `<div *ngIf="_svg" [innerHTML]="trustAsHtml(_svg)" class="svg-container embedded"></div>`,
        providers: [ReplaceAllPipe, BetweenPipe]
    })

    export class SvgTemplateComponent implements OnChanges {
        @Input() private src: string;
        @Input() private data: any = {};
        @Output() public loaded: EventEmitter<any> = new EventEmitter();

        private settings;
        public _svg: any;
        private _svgElement: any;
        private _dataCurrent: any;
        private _dataNew: any;
        private _containerElements: any = {};
        private _src: string;
        public el: HTMLElement;
        public type: string;

        constructor(private baseService: BaseService, public elementRef: ElementRef, private http: Http, private renderer: Renderer, private _sanitizer: DomSanitizer, private replaceAll: ReplaceAllPipe, private betweenPipe: BetweenPipe) {
            // super(baseService)
        }

        ngOnInit() {
            this.settings = this.baseService.settings;
            this.el = this.elementRef.nativeElement;
            this.type = 'template';
            this._src = this.src;
            this.loadSvg();
        }

        ngOnChanges(changes) {
            this._dataNew = this._dataCurrent = this.data;
            // console.log(changes);
            // if (changes.data) {
            //     console.log('ngOnChanges',changes.data);
            //     if (!this._dataCurrent) {
            //         this._dataCurrent = JSON.parse(JSON.stringify(changes.data.currentValue));
            //     }
            //     this._dataNew = JSON.parse(JSON.stringify(changes.data.currentValue));
            //     for(let k in this._dataNew){
            //         this.data[k]=this._dataNew[k];
            //     }
            //     this._dataNew = this._dataCurrent = this.data;
            //     console.log(this._dataNew.title);
            //     if (this.type === 'template') {
            //         this.renderData();
            //         this.renderTemplateData();
            //     } else {
            //         this.renderData();
            //     }
            // }
        }

        initSvg(svgElement) {
            this._svgElement = svgElement;
        }

        renderTemplateData() {
            // type: svg-template
            const self = this;
            const obj: any = this.data;
            if (self._dataNew) {
                const objNew = self._dataNew;
                Object.keys(objNew).forEach(function (keyNew) {
                    const newValue = obj[keyNew];
                    const objCurrent = self._dataCurrent;
                    Object.keys(objCurrent).forEach(function (keyCurrent) {
                        const currentValue = objCurrent[keyCurrent];
                        if (keyNew === keyCurrent) {
                            self._svg = self.replaceAll.transform(self._svg, '<!--data-->' + currentValue + '<!--end:data-->', '<!--data-->' + newValue + '<!--end:data-->');
                        }
                    });
                    // set new data properties
                    self._svg = self.replaceAll.transform(self._svg, '{{' + keyNew + '}}', '<!--data-->' + newValue + '<!--end:data-->');
                });
                this._dataCurrent = this._dataNew;
            }
            setTimeout(() => {
                this.centerSketchUIText();
            }, 100);
            // todo: hide empty
            // console.log(self.betweenPipe.transform(self._svg, '{{','}}'));
        }

        renderData() {
            // type: svg-app
            const self = this;
            if (!this.data) {
                return;
            }
            Object.keys(this.data).forEach(function (key) {
                self[key] = self.data[key];
            });
        }

        renderSvg() {
            const self = this;
            const $svg = this._svgElement;
            const responsive = !(this.el.className.indexOf('img-responsive') === -1) ;
            let viewBox;
            if ($svg.getAttribute('viewBox')) {
                viewBox = $svg.getAttribute('viewBox');
            }
            // console.log('--------------');
            // console.log('svg: type=' + this.type);
            // console.log('responsive=' + responsive);
            let w, h;
            // fixme ??
            if (viewBox) {
                w = viewBox.split(' ')[2];
                h = viewBox.split(' ')[3];
                if (responsive === false) {
                    // 100%
                    this.el.style.width = w + 'px';
                    this.el.style.maxWidth = w + 'px';
                    this.el.style.height = h + 'px';
                    this.el.style.maxHeight = h + 'px';
                    $svg.style.width = w + 'px';
                    $svg.style.maxWidth = w + 'px';
                    $svg.style.height = h + 'px';
                    $svg.style.maxHeight = h + 'px';

                    let att;
                    att = document.createAttribute('width');
                    att.value = w;
                    // att.value = w+'px';
                    $svg.setAttributeNode(att);
                    att = document.createAttribute('height');
                    att.value = h;
                    // att.value = h+'px';
                    $svg.setAttributeNode(att);
                }
                // console.log($svg.getAttribute('width'));
                // console.log($svg.getAttribute('height'));
            }

              // replace Illustrator fonts: fixme: check + remove jQuery dependency
              if (this.settings.font_replace_map && (<any>window)['$']) {
                _.each(this.settings.font_replace_map, function(obj){
                  _.each(obj, function(v, k){
                    // presentation export:
                    $(self.el).find('svg text').each(function(){
                      if ($(this).attr('font-family')) {
                        if ($(this).attr('font-family').match(k)) {
                                // console.log('v',v);
                                // console.log('k',k);
                          $(this).attr('font-family', $(this).attr('font-family').replace(k, v));
                          $(this).css('font-family:' + v);
                        }
                      }
                    });
                    // styles export:
                    $(self.el).find('svg style').each(function(){
                      $(this).text($(this).text().replace(k, v));
                    });
                  });
                });
              }
        }

        prepareLoadedSvg(svgResult: string) {
            if (this.type === 'template') {
                // fixes Illustrator weird character display bug.
                svgResult = svgResult.replace(']>', '');
                // remove whitespaces around data properties
                svgResult = this.replaceAll.transform(svgResult, '{{ ', '{{');
                svgResult = this.replaceAll.transform(svgResult, '{{  ', '{{');
                svgResult = this.replaceAll.transform(svgResult, '{{   ', '{{');
                svgResult = this.replaceAll.transform(svgResult, ' }}', '}}');
                svgResult = this.replaceAll.transform(svgResult, '  }}', '}}');
                svgResult = this.replaceAll.transform(svgResult, '   }}', '}}');
                this._svg = svgResult;
                const timer = setInterval(() => {
                    if (this.el.querySelector('svg')) {
                        this.initSvg(this.el.querySelector('svg'));
                        this.renderSvg();
                        if (this.type === 'template') {
                            if (this.loaded) {
                                this.loaded.emit('svg-loaded');
                            }
                            this.renderTemplateData();
                        }
                        if (this.type === 'embedded') {
                            // fix to hide xml tag display ??
                            this.el.style.fontSize = '0';
                            // let positionCorrection = 0 - this._svgElement.getBoundingClientRect().left + this.el.getBoundingClientRect().left;
                            // this.el.style.marginLeft = positionCorrection+'px';
                            // this.el.style.overflowX = 'hidden';
                            if (this.loaded) {
                                this.loaded.emit('svg-loaded');
                            }
                        }
                        clearInterval(timer);
                    }
                }, 50);
                return;
            }
        }

        loadSvg() {
            if (this.src) {
                this.http.get(this.src)
                    .subscribe(
                        (res: Response) => {
                            this.prepareLoadedSvg(res.text());
                        },
                        err => {
                            console.error(err);
                        }
                    );
            }
        }

        // fixme: cannot change svg attributes
        centerSketchUIText() {
            const self = this;
            if (!this._svg && !this.data) {
                return;
            }
            if (!this.el.querySelectorAll("[id*='UI']").length) {
                return;
            }
            // let $el;
            // $el = this.el;
            //
            // Object.keys(this.data).forEach((key) => {
            //     // const value = this.data[key];
            //     let idSelector = '{{-'+key+'-}}';
            //     let query = "[id*='"+idSelector+"']";
            //     let containerElements = [];
            //     // if (self.el.querySelectorAll(query).length){
            //     if ($el.querySelectorAll(query).length){
            //         if(!self._containerElements[query]){
            //             self._containerElements[query] = [];
            //         }
            //         self._containerElements[query] = $el.querySelectorAll(query);
            //
            //         console.log(query);
            //         console.log('matches='+$el.querySelectorAll(query).length);
            //
            //         if(self._containerElements[query].length){
            //             _.each(self._containerElements[query],(container)=>{
            //                 let el = container;
            //
            //                 let BG = container.querySelectorAll("[id*='BG']")[0];
            //                 let BGAttrs = {id:''};
            //                 let BGBox = BG.getBBox()
            //                 Object.keys(BG.attributes).forEach((key) => {
            //                     BGAttrs[BG.attributes[key].name]=BG.attributes[key].value;
            //                 });
            //                 console.log('---------');
            //                 console.log('BG.BGAttrs',BGAttrs);
            //                 console.log('BG.getBBox',BGBox);
            //
            //                 let text = container.querySelectorAll("text")[0];
            //                 let textAttrs = {id:''};
            //                 let textBBox = text.getBBox()
            //                 Object.keys(text.attributes).forEach((key) => {
            //                     textAttrs[text.attributes[key].name]=text.attributes[key].value;
            //                 });
            //                 console.log('---------');
            //                 console.log('text',textAttrs);
            //                 console.log('text.getBBox',textBBox);
            //
            //                 let tspan = container.querySelectorAll("tspan")[0];
            //                 let tspanAttrs = {};
            //                 let tspanBBox = tspan.getBBox()
            //                 Object.keys(tspan.attributes).forEach((key) => {
            //                     tspanAttrs[tspan.attributes[key].name]=tspan.attributes[key].value;
            //                 });
            //                 console.log('---------');
            //                 console.log('tspan',tspanAttrs);
            //                 console.log('tspan.getBBox',tspanBBox);
            //
            //                 console.log('===============');
            //                 console.log('BG',self.svgCalculateSize(BG));
            //                 console.log('text',self.svgCalculateSize(text));
            //                 console.log('tspan'+self.svgCalculateSize(tspan));
            //
            //                 setTimeout(()=>{
            //                     // fixme:
            //                     console.log('fixme:----- set ------');
            //                     console.log($(tspan).attr('x'));
            //                     console.log($(tspan).attr('y'));
            //                     // console.log(tspan);
            //                     tspan.setAttribute("x", "0");
            //                     tspan.setAttribute("y", "0");
            //                     console.log($(tspan).attr('x'));
            //                     console.log($(tspan).attr('y'));
            //                     console.log(tspan.attributes);
            //                 },1000)
            //
            //                 // tspanAttrs['x']=0;
            //                 // console.log(tspanAttrs);
            //                 // console.log('x',tspan.x.animVal[0].value);
            //                 // console.log('x',tspan.x.animVal[0].valueAsString);
            //                 // console.log('y',tspan.y);
            //                 // console.log('textLength',tspan.textLength);
            //                 // console.log(tspan.offsetWidth);
            //                 // console.log(tspan.offsetHeight);
            //                 // tspan
            //
            //             });
            //             // console.log(containerElements);
            //         }
            //
            //     };
            // });
            //
            // console.log(self);
            // console.log(self._containerElements);

        }

        svgCalculateSize(svg) {
            // svg.style.display='block';
            // svg.style.display='none';

            let svgWidth = svg.clientWidth || window.getComputedStyle(svg).width;
            let svgHeight = svg.clientHeight || window.getComputedStyle(svg).height;
            // let svgWidth = $(svg).width();
            // let svgHeight =$(svg).height();

            return({width: svgWidth, height: svgHeight});

            // let heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'];
            // let widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];
            //
            // let gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
            //     bounds = {
            //         width: 0,
            //         height: 0
            //     };
            //
            // heightComponents.forEach(function (css) {
            //     bounds.height += parseFloat(gCS[css]);
            // });
            // widthComponents.forEach(function (css) {
            //     bounds.width += parseFloat(gCS[css]);
            // });
            // return bounds;
        };

        trustAsHtml(content) {
            return this._sanitizer.bypassSecurityTrustHtml(content) as SafeHtml;
        };

    }

Legend
Html element
Component
Html element with directive

# results matching ""

# No results matching ""