Angular 2 다른 모듈의 컴포넌트 사용
angular-cli로 생성 된 Angular 2 (버전 2.0.0-최종) 앱이 있습니다.
구성 요소를 만들고 AppModule선언 배열에 추가하면 모두 작동합니다.
구성 요소를 분리하기로 결정 했으므로 TaskModule및 구성 요소를 만들었습니다 TaskCard. 이제 ( 구성 요소) 의 구성 TaskCard요소 중 하나에서 를 사용하고 싶습니다 .AppModuleBoard
앱 모듈 :
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { BoardComponent } from './board/board.component';
import { LoginComponent } from './login/login.component';
import { MdButtonModule } from '@angular2-material/button';
import { MdInputModule } from '@angular2-material/input';
import { MdToolbarModule } from '@angular2-material/toolbar';
import { routing, appRoutingProviders} from './app.routing';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { UserService } from './services/user/user.service';
import { TaskModule } from './task/task.module';
@NgModule({
declarations: [
AppComponent,
BoardComponent,// I want to use TaskCard in this component
LoginComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MdButtonModule,
MdInputModule,
MdToolbarModule,
routing,
TaskModule // TaskCard is in this module
],
providers: [UserService],
bootstrap: [AppComponent]
})
export class AppModule { }
작업 모듈 :
import { NgModule } from '@angular/core';
import { TaskCardComponent } from './task-card/task-card.component';
import { MdCardModule } from '@angular2-material/card';
@NgModule({
declarations: [TaskCardComponent],
imports: [MdCardModule],
providers: []
})
export class TaskModule{}
전체 프로젝트는 https://github.com/evgdim/angular2(kanban-board 폴더)에 있습니다.
내가 뭘 놓친거야? 내가 사용하는 할 필요가 TaskCardComponent있는 BoardComponent?
여기서 주요 규칙은 다음과 같습니다.
컴포넌트 템플릿 컴파일 중에 적용 할 수있는 선택기는 해당 컴포넌트를 선언하는 모듈과 해당 모듈 가져 오기 내보내기의 전이 폐쇄에 의해 결정됩니다.
따라서 내보내십시오.
@NgModule({
declarations: [TaskCardComponent],
imports: [MdCardModule],
exports: [TaskCardComponent] <== this line
})
export class TaskModule{}
무엇을 내 보내야합니까?
다른 모듈의 구성 요소가 해당 템플릿에서 참조 할 수 있어야하는 선언 가능한 클래스를 내 보냅니다. 이들은 당신의 공개 수업입니다. 클래스를 내 보내지 않으면 비공개로 유지되며이 모듈에 선언 된 다른 구성 요소에만 표시됩니다.
새 모듈을 만들거나, 새 모듈을 만들거나, 새 모듈을 만들고 그 모듈에 아무것도 선언하면 새 모듈은 깨끗한 상태를 갖습니다 (Ward Bell이 https://devchat.tv/adv-in-angular/119 에서 말했듯이) -aia-avoiding- 공통 함정-각도 2 )
Angular 는 각각에 대해 전이 모듈 을 만듭니다 @NgModule.
이 모듈 은 다른 모듈 (가져온 모듈의 전이 모듈이 지시어를 내 보낸 경우)에서 가져 오거나 현재 모듈에 선언 된 지시문을 수집합니다 .
angular가 모듈에 속하는 템플릿을 컴파일 할 때 X.transitiveModule.directivesX 에서 수집 된 지시문이 사용됩니다 .
compiledTemplate = new CompiledTemplate(
false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
https://github.com/angular/angular/blob/4.2.x/packages/compiler/src/jit/compiler.ts#L250-L251
위의 그림에 따르면
YComponent사용할 수ZComponent있기 때문에 그 템플릿directives의 배열이Transitive module Y포함되어 있지 않습니다ZComponent때문에YModule수입되지 않은ZModule그의 이적 모듈 포함ZComponent에exportedDirectives배열입니다.Within
XComponenttemplate we can useZComponentbecauseTransitive module Xhas directives array that containsZComponentbecauseXModuleimports module (YModule) that exports module (ZModule) that exports directiveZComponentWithin
AppComponenttemplate we can't useXComponentbecauseAppModuleimportsXModulebutXModuledoesn't exportsXComponent.
See also
why lazy loaded module has to import commonModule? Angular 2
- What is difference between declarations, providers and import in NgModule
You have to export it from your NgModule:
@NgModule({
declarations: [TaskCardComponent],
exports: [TaskCardComponent],
imports: [MdCardModule],
providers: []
})
export class TaskModule{}
(Angular 2 - Angular 7)
Component can be declared in a single module only. In order to use a component from another module, you need to do two simple tasks:
- Export the component in the other module
- Import the other module, into the current module
1st Module:
Have a component (lets call it: "ImportantCopmonent"), we want to re-use in the 2nd Module's page.
@NgModule({
declarations: [
FirstPage,
ImportantCopmonent // <-- Enable using the component html tag in current module
],
imports: [
IonicPageModule.forChild(NotImportantPage),
TranslateModule.forChild(),
],
exports: [
FirstPage,
ImportantCopmonent // <--- Enable using the component in other modules
]
})
export class FirstPageModule { }
2nd Module:
Reuses the "ImportantCopmonent", by importing the FirstPageModule
@NgModule({
declarations: [
SecondPage,
Example2ndComponent,
Example3rdComponent
],
imports: [
IonicPageModule.forChild(SecondPage),
TranslateModule.forChild(),
FirstPageModule // <--- this Imports the source module, with its exports
],
exports: [
SecondPage,
]
})
export class SecondPageModule { }
Note that in order to create a so called "feature module", you need to import CommonModule inside it. So, your module initialization code will look like this:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TaskCardComponent } from './task-card/task-card.component';
import { MdCardModule } from '@angular2-material/card';
@NgModule({
imports: [
CommonModule,
MdCardModule
],
declarations: [
TaskCardComponent
],
exports: [
TaskCardComponent
]
})
export class TaskModule { }
More information available here: https://angular.io/guide/ngmodule#create-the-feature-module
Whatever you want to use from another module, just put it in the export array. Like this-
@NgModule({
declarations: [TaskCardComponent],
exports: [TaskCardComponent],
imports: [MdCardModule]
})
SOLVED HOW TO USE A COMPONENT DECLARED IN A MODULE IN OTHER MODULE.
Based on Royi Namir explanation (Thank you so much). There is a missing part to reuse a component declared in a Module in any other module while lazy loading is used.
1 차 : 컴포넌트를 포함하는 모듈에서 컴포넌트를 내 보냅니다.
@NgModule({
declarations: [TaskCardComponent],
imports: [MdCardModule],
exports: [TaskCardComponent] <== this line
})
export class TaskModule{}
두 번째 : TaskCardComponent를 사용하려는 모듈에서 :
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdCardModule } from '@angular2-material/card';
@NgModule({
imports: [
CommonModule,
MdCardModule
],
providers: [],
exports:[ MdCardModule ] <== this line
})
export class TaskModule{}
이와 같이 두 번째 모듈은 구성 요소를 가져오고 내보내는 첫 번째 모듈을 가져옵니다.
두 번째 모듈에서 모듈을 가져 오면 다시 내 보내야합니다. 이제 두 번째 모듈의 첫 번째 구성 요소를 사용할 수 있습니다.
하나의 크고 훌륭한 접근 방법은에서 모듈을 NgModuleFactory로드하는 것입니다.이를 호출하여 다른 모듈 안에 모듈을로드 할 수 있습니다.
constructor(private loader: NgModuleFactoryLoader, private injector: Injector) {}
loadModule(path: string) {
this.loader.load(path).then((moduleFactory: NgModuleFactory<any>) => {
const entryComponent = (<any>moduleFactory.moduleType).entry;
const moduleRef = moduleFactory.create(this.injector);
const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);
this.lazyOutlet.createComponent(compFactory);
});
}
나는 여기 에서 이것을 얻었다 .
참고 URL : https://stackoverflow.com/questions/39601784/angular-2-use-component-from-another-module
'Programing' 카테고리의 다른 글
| Picasso를 사용하여 이미지를 전체 너비 및 고정 높이로 크기 조정 (0) | 2020.05.31 |
|---|---|
| .ToList (), .AsEnumerable (), AsQueryable ()의 차이점은 무엇입니까? (0) | 2020.05.30 |
| Express에서 멋진 형식의 HTML을 출력하려면 어떻게해야합니까? (0) | 2020.05.30 |
| 문자열을 n 문자 세그먼트로 나누려면 어떻게해야합니까? (0) | 2020.05.30 |
| V8에서이 코드 스 니펫을 사용하여 <=가 <보다 느린 이유는 무엇입니까? (0) | 2020.05.30 |
