Skip to content

spoznamkovane problemy pri tvorbe angular2 appiek pomocou angular-cli alebo inych seedov

Notifications You must be signed in to change notification settings

IcodeNet/HowToAngular2

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 

Repository files navigation

HowToAngular2

spoznamkovane problemy pri tvorbe angular2 appiek pomocou angular-cli alebo inych seedov

[Angular] Window resize event

import 'rxjs/add/operator/debounceTime';
import 'reflect-metadata';

@HostListener('window:resize', ['$event']) // in component, trigger ChangeDetector if onPush strategy is used
  onWindowResize(event) {
    // this.windowResizeEvent$.next(event);
  }

[Angular] Base Tag for production on build

# Sets base tag href to /myUrl/ in your index.html
ng build --base-href /myUrl/
ng build --bh /myUrl/

[Angular] Dynamic Base tag for NgRouter

<script>document.write('<base href="' + document.location + '" />');</script>

[Angular] Elegant way to unsubscribe Observables

@Component({
  selector: 'blah',
  template: 'blah',
})
export class MyComponent {
  private onDestroy$ = new Subject();

  constructor(http: Http) {
    // Use .takeUntil() instead of tracking subscriptions manually. This should be the last
    // operator before .subscribe().
    http.get('/url').takeUntil(this.onDestroy$).subscribe(...);
  }

  ngOnDestroy() {
    // Clean up all subscriptions at once:
    this.onDestroy$.next();
    this.onDestroy$.complete();
  }
}

[Angular] How to create Angula library

SYNC version:

/// some.module.ts
import { NgModule } from '@angular/core';

import { SomeComponent }   from './some.component';

@NgModule({
    imports: [],
    exports: [],
    declarations: [SomeComponent],
    providers: [ MyService ], // <======================= PROVIDE THE SERVICE
})
export class SomeModule { }
/// some-other.module.ts
import { NgModule } from '@angular/core';

import { SomeModule } from 'path/to/some.module'; // <=== IMPORT THE JSMODULE

import { SomeOtherComponent }   from './some.other.component';

@NgModule({
    imports: [ SomeModule ], // <======================== IMPORT THE NG MODULE
    exports: [],
    declarations: [SomeOtherComponent],
    providers: [],
})
export class SomeOtherModule { }

ASYNC version (lazy loading) with forRoot pattern:

[Angular] How create custom Input/Output property, ngModel

import {Component, EventEmitter, Input, Output} from 'angular2/core'

@Component({
    selector: 'child',
    template: `
        <p>Child sharedVar: {{sharedVar}}</p>
        <input [ngModel]="sharedVar" (ngModelChange)="change($event)">
    `
})
export class ChildComponent {
    @Input() sharedVar: string;
    @Output() sharedVarChange = new EventEmitter();
    change(newValue) {
      console.log('newvalue', newValue)
      this.sharedVar = newValue;
      this.sharedVarChange.emit(newValue);
    }
}

@Component({
    selector: 'parent',
    template: `
        <div>Parent sharedVarParent: {{sharedVarParent}}</div>
        <child [(sharedVar)]="sharedVarParent"></child>
    `,
    directives: [ChildComponent]
})
export class ParentComponent {
    sharedVarParent ='hello';
    constructor() { console.clear(); }
}

[Angular] How trigger change detection when 'ChangeDetectionStrategy.OnPush'

  • this._changeDetectorRef.detectChanges();
  • observable or ngZone.run() trigger tick and change automatically

[Angular] How expose angular 2 methods / call from outside of angular2 ?

[Angular] Pre-Bootstraping template

  • vsetko v angular directive bude vymazane po na-bootstrap-ovani angular appky
  • logo/image ako byte array https://www.base64-image.de/ - vynecha dodatocny request pre obrazok v boostrap template-e

[Angular] Real debounce on input element

[Angular] Ako pouzit jQuery v komponente

declare var jQuery: any;
//...
@ViewChild('checkbox') checkbox: ElementRef;
//...
ngAfterViewInit() {
  jQuery(this.checkbox.nativeElement).checkbox(this.isPredefined ? 'set checked' : 'set unchecked');
}

[Angular] How load config from server before bootstraping

@Injectable()
export class ConfigService {
  static DASHBOARD_CONFIG_ADDRESS = 'dashboard-configuration.json';

  private _config: Config;

  constructor(private http: Http) { }

  loadConfig(): Promise<Config> {
    const serviceThat = this;

    return new Promise((resolve) => {
      this.http.get(ConfigService.DASHBOARD_CONFIG_ADDRESS).map(res => res.json()).toPromise()
        .then((configResponse) => {
          serviceThat._config = configResponse;
          console.info('[ConfigService] dashboard configuration: ' + JSON.stringify(configResponse));
          resolve();
        })
        .catch(() => {
          console.error('[ConfigService] could not get dashboard configuration !');
          resolve();
        });
    });
  }

  getConfig(): Config {
    return this._config;
  }

}


//module js file
export function loadConfigFn(configService: ConfigService) {
  return () => configService.loadConfig();
}

@NgModule({
providers: [
    FetchingService,
    ConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: loadConfigFn,
      deps: [ConfigService],
      multi: true,
    }
  ]
})

[angular-cli] Webpack Warning that export 'INTERFACE' was not found

  • workaround angular/angular-cli#2034
    • interfaces folder with index.ts that export all interfaces manually
    • split each interface into separate file

[angular-cli] Integration of Font-Awesome (External css lib with url to fonts)

  • pridal som v angular-cli.json style hodnotu, cesta na node_modules min css, URLs vo vnutry css-iek sa po kompilacii angular-cli poriesili a dotahali fonty ako assets

[Chrome] debug Devpanel/Devtools ako chrome extension ?

[Chrome] Angular app ako chrome extension (devpanel) nefunguje bootstraping ?

  • Unhandled Promise rejection: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". ; Zone: <root> ; Task: Promise.then ; Value: EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:".
  • https://www.sitepoint.com/chrome-extension-angular-2/
  • "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'" vyriesilo moj problem

[ImmutableJS] object as Observable value trick

  • ngrx/store#233
  • _store.select('counter').map((immuObj: List<any>) => immuObj.toJS())

[ImmutableJS] neviem pracovat s Typescript getters() setters() !!

class foo {
    private _bar:boolean = false;
    get bar():boolean {
        return this._bar;
    }
    set bar(theBar:boolean) {
        this._bar = theBar;
    }
}

[TypeScript] Property 'map' does not exist on type 'Observable'

import 'rxjs/add/operator/map';

[TypeScript] Ako explicitne setnem hodnotu na window objekt ?

[Typescript] nepozna chrome window objekt

  • declare var chrome: any; at top and ignore it

[Rxjs] Simple observable exmaple

private windowResizeEvent$: BehaviorSubject<number> = new BehaviorSubject(window.innerHeight);

@HostListener('window:resize', ['$event.target.innerHeight'])
  onWindowResize(innerHeight: number) {
    this.windowResizeEvent$.next(innerHeight);
  }

this.windowResizeEvent$
     .debounceTime(10) //GRYF throttling !
     .subscribe((windowInnerHeight) => {
       this.calculateIFrameHeight(windowInnerHeight);
     });

About

spoznamkovane problemy pri tvorbe angular2 appiek pomocou angular-cli alebo inych seedov

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published