developer tip

$ document.ready ()에 해당하는 Angular2

optionbox 2020. 10. 8. 07:55
반응형

$ document.ready ()에 해당하는 Angular2


간단한 질문입니다.

$ document.ready ()에 해당하는 Angular2가 실행될 때 스크립트를 실행하고 싶습니다. 이를 달성하는 가장 좋은 방법은 무엇입니까?

의 끝에 스크립트를 넣으려고했지만 알다시피 index.html작동하지 않습니다! 나는 그것이 어떤 종류의 구성 요소 선언에 들어가야한다고 생각합니까?

.js파일 에서 스크립트로드를 실행할 수 있습니까?

편집-코드 :

내 응용 프로그램에 삽입 된 다음 js 및 css 플러그인이 있습니다 ( Foundry html 테마에서 ).

    <link href="css/themify-icons.css" rel="stylesheet" type="text/css" media="all" />
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" />
    ...


    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/flexslider.min.js"></script>
    ...
    <script src="js/scripts.js"></script> //This initiates all the plugins

앞서 언급했듯이 scripts.js는 모든 것을 '인스턴스화'하므로 Angular가 준비된 후에 실행해야합니다. script.js

작동 :

import {Component, AfterViewInit} from 'angular2/core';

@Component({
  selector: 'home',
  templateUrl: './components/home/home.html'
})
export class HomeCmp implements AfterViewInit {


    ngAfterViewInit() {
       //Copy in all the js code from the script.js. Typescript will complain but it works just fine
    }

ngOnInit()Angular 루트 구성 요소 에서 직접 이벤트를 시작한 다음 Angular 외부에서이 이벤트를 수신 할 수 있습니다 .

이것은 Dart 코드 (TypeScript를 모릅니다)이지만 번역하기 어렵지 않아야합니다.

@Component(selector: 'app-element')
@View(
    templateUrl: 'app_element.html',
)
class AppElement implements OnInit {
  ElementRef elementRef;
  AppElement(this.elementRef);

  void ngOnInit() {
    DOM.dispatchEvent(elementRef.nativeElement, new CustomEvent('angular-ready'));
  }
}

Chris의 답변 복사 :

작동 :

import {AfterViewInit} from 'angular2/core';    

export class HomeCmp implements AfterViewInit {    

    ngAfterViewInit() {
       //Copy in all the js code from the script.js. Typescript will complain but it works just fine
    }

이 솔루션을 사용했기 때문에 jQuery $ .getScript 함수 이외의 구성 요소 내에 사용자 지정 js 코드를 포함 할 필요가 없었습니다 .

참고 : jQuery에 대한 종속성이 있습니다. 따라서 jQuery 및 jQuery 타이핑이 필요합니다.

이것은 TypeScript가 앱을 시작할 때 비명을 지르지 않는 방식으로 사용할 수있는 타이핑이없는 사용자 지정 또는 공급 업체 js 파일을 처리하는 좋은 방법이라는 것을 발견했습니다.

import { Component,AfterViewInit} from '@angular/core'

@Component({
  selector: 'ssContent',
  templateUrl: 'app/content/content.html',
})
export class ContentComponent implements AfterViewInit  {

  ngAfterViewInit(){
    $.getScript('../js/myjsfile.js');
  }
}

Update Actually in my scenario the OnInit lifecycle event worked better because it prevented the script from loading after the views were loaded, which was the case with ngAfterViewInit, and that cause the view to show incorrect element positions prior to the script loading.

ngOnInit() {
    $.getScript('../js/mimity.js');
  }

In order to use jQuery inside Angular only declare the $ as following: declare var $: any;


the accepted answer is not correct, and it makes no sens to accept it considering the question

ngAfterViewInit will trigger when the DOM is ready

whine ngOnInit will trigger when the page component is only starting to be created


In your main.ts file bootstrap after DOMContentLoaded so angular will load when DOM is fully loaded.

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}



document.addEventListener('DOMContentLoaded', () => {
  platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));
});

참고URL : https://stackoverflow.com/questions/34547127/angular2-equivalent-of-document-ready

반응형