Angular-CLI를 사용하여 특정 모듈에 컴포넌트 작성


170

나는 angular-cli를 사용하기 시작했고 이미하고 싶은 것에 대한 답을 찾기 위해 많은 것을 읽었습니다 ... 성공하지 않기 때문에 여기에 왔습니다.

새 모듈에 컴포넌트를 작성하는 방법이 있습니까?

예 : ng g module newModule

ng g component newComponent (이 컴포넌트를 newModule에 추가하는 방법 ??)

angular-cli 기본 동작은 모든 새 구성 요소를 안에 넣는 것 app.module입니다. 구성 요소를 배치 할 위치를 선택하여 분리 된 모듈을 만들 수 있으며 내부에 모든 구성 요소가 포함되어 있지 않습니다 app.module. angular-cli를 사용하여 수행 할 수 있습니까? 아니면 수동으로 수행해야합니까?

답변:


216

모듈의 일부로 구성 요소를 작성하려면

  1. ng g module newModule 모듈을 생성하기 위해
  2. cd newModule디렉토리를 newModule폴더 로 변경
  3. ng g component newComponent 구성 요소를 모듈의 하위로 작성합니다.

업데이트 : 각도 9

이제 컴포넌트를 생성 할 때 어떤 폴더에 있는지는 중요하지 않습니다.

  1. ng g module NewMoudle 모듈을 생성합니다.
  2. ng g component new-module/new-component NewComponent를 생성합니다.

참고 : Angular CLI는 새 모듈 / 새 구성 요소를 볼 때 새 모듈-> NewModule 및 새 구성 요소-> NewComponent와 일치하는 경우를 이해하고 변환합니다. 처음에는 혼란 스러울 수 있으므로 # 2의 이름을 모듈 및 구성 요소의 폴더 이름과 일치시키는 쉬운 방법입니다.


92
또한 프로젝트 루트에 그대로두고 모듈 이름 앞에 구성 요소를 접두어로 붙일 수 ng g component moduleName/componentName있습니다.
— JayChase

3
Angular CLI 버전 1.6.8에서는 기존 모듈을 구분할 때 항상 '지정된 모듈이 존재하지 않습니다'라는 오류 메시지가 나타납니다. ng generate service service1 --module = module1 / module1.module.ts 명령을 시도했을 때 작동했습니다 . 참고 : 내 서비스 이름은 service1 이고 내 모듈 이름은 module1
— Diallo

8
지정된 디렉토리에 새 구성 요소가 작성되지만 모듈에 등록되지는 않습니다. app.module에 등록합니다. 다음 --module과 같은 옵션으로 모듈을 지정해야합니다 .ng g component <your component> --module=<your module name>
— Vinit Sarvade

3
10 월 6 일 현재, Angular 6
— tom87416

4
시대에 뒤쳐진. Angular 6은 구성 요소가 어떤 모듈인지 확인하기 위해 폴더 구조에 의존하지 않습니다. 두 개의 모듈이 같은 디렉토리에있을 수 있습니다.
— @daniel

145
ng g component nameComponent --module=app.module.ts

10
다른 답변은 효과가 있지만 이것이 가장 효율적입니다. 추가 그것의 가치가 --dry-run바로 영향을받는 것을보고 그 끝에, 그것은 멋진 전성 검사의
— tony09uk

ng g component path/to/myComponent --module=app.module.ts --dry-run매우 유용한 명령입니다. 컴포넌트가 올바른 디렉토리에 작성되었는지 확인하십시오.
— theman0123

74

글을 쓰는 시점에서 Alexander Ciesielski의 답변이 정확한지 확실하지 않지만 더 이상 작동하지 않는지 확인할 수 있습니다. Angular CLI를 실행하는 프로젝트의 디렉토리는 중요하지 않습니다. 입력하면

ng g component newComponent

컴포넌트를 생성하고 app.module.ts 파일로 가져옵니다.

CLI를 사용하여 다른 모듈로 자동으로 가져올 수있는 유일한 방법은 다음을 지정하는 것입니다.

ng g component moduleName/newComponent

여기서 moduleName은 프로젝트에서 이미 정의한 모듈입니다. moduleName이 존재하지 않으면 componentName / newComponent 디렉토리에 컴포넌트를 배치하지만 여전히 app.module로 가져옵니다.


2
당시에는 제게 정답이었습니다. 제대로 작동합니다. 이 정보를 문서에 추가하기 위해 풀 요청을 만듭니다. 그것의 기여 중 하나는 1이 될 것이다 제거는 최종 part..in CD-보내고에게 물어 ng g module newModule 2. ng g component new-module/newComponent그 대신 newModule의 새로운 모듈해야에 따라
— 엘머 Dantas

Alexander Ciesielski의 기술을 사용하여 예상대로 작동합니다. 폴더를 만드는 데 필요한 구성 요소를 만들 필요가 없었습니다. 그래서 나는 단지 mkdir폴더를 만들고 새로 만든 폴더 안에 newComponent 구성 요소를 실행했습니다.
— Charlie-Greenman

2
전체 답변은 다음과 같습니다.ng g component moduleName/newComponent -m moduleName
— slavugan

내 경우에는 구성 요소 이름이 모듈 이름과 동일하므로 ng generate module {modComName}1) 폴더를 만들었습니다. 2) 동일한 이름의 폴더 안에 모듈 파일을 만들었습니다. ng generate component {modComName}실제로 명령 1) 같은 이름의 폴더 안에 구성 요소 파일을 만들었습니다. 2) 구성 요소를 가져 오기 위해 모듈 수정
— Red Pea

모듈을 작성하여 기본 모듈로 가져 오는 경우주의하십시오. 배열 끝에ng 가져 오기를 추가합니다 . 그러나 당신은 원할지도 모릅니다 : "구성의 경로 순서는 중요하며 이것은 의도적으로 설계된 것입니다."
— 붉은 완두콩

37

cli를 사용하여 최상위 모듈 폴더 내에 구성 요소를 생성하고 구성 요소가 모듈의 선언 컬렉션을 자동으로 추가하는 방법을 보여주는 답변을 찾지 못했습니다.

모듈을 만들려면 다음을 실행하십시오.

ng g module foo

foo 모듈 폴더 내에 컴포넌트를 작성하고 foo.module.ts의 선언 콜렉션에 추가하려면 다음을 실행하십시오.

ng g component foo/fooList --module=foo.module.ts

그리고 cli는 다음과 같이 모듈과 컴포넌트를 스캐 폴딩합니다 :

여기에 이미지 설명을 입력하십시오

-각도 클리의 새 버전 편집은 다르게 작동합니다. 1.5.5는 모듈 파일 이름을 원하지 않으므로 v1.5.5의 명령은

ng g component foo/fooList --module=foo

1
예, --module논쟁에 대한; 문서는 "선언 모듈의 사양을 수 있습니다"라고 말합니다. ; 내가 추가 할 수 --module지정 기존 모듈이해야 수정 당신이 모듈 가져 만드는 대해
— 레드 완두콩

2
@TheRedPea 나는 당신이 "--module 당신이있는 컴포넌트를 가져 오기 위해 어떤 기존의 모듈을 수정해야 하는지를 지정한다"라고 생각한다고 믿는다.
— cobolstinks

네 맞아요! 새로운 구성 요소
— The Red Pea

13

아래 명령을 시도해보십시오.

ng -> Angular 
g  -> Generate
c  -> Component
-m -> Module 

그런 다음 명령은 다음과 같습니다.

ng g c user/userComponent -m user.module

9

Angular v4 이상의 경우 다음을 사용하십시오.

ng g c componentName -m ModuleName

1
Specified module does not exist모듈이 존재 하는 동안 오류 발생
— Pardeep Jain

1
모듈 이름을 지정하지 않고 모듈의 파일 이름을 지정합니다.
— Roger

1
매력처럼 작동합니다! 예를 들어 모듈 파일이 user-settings.module.ts있고 컴포넌트를 추가하려는 public-info경우 명령은 다음과 같습니다.ng g c PublicInfo -m user-settings
— Spiral Out

1
가장 간단하고 깨끗한 답변입니다!
— Barna Tekse

8

이것이 나를 위해 일한 것입니다.

1 -->  ng g module new-module

2 -->  ng g c new-module/component-test --module=new-module/new-module.module.ts

디렉토리없이 구성 요소를 생성하려면 --flat 플래그를 사용하십시오 .


.ts를 쓸 필요가 없습니다
— Lapenkov Vladimir

--module = path-to-module 모듈 덕분에 @Mohamed Makkaoui
— Ian Poston Framer

8
  1. 먼저 실행하여 모듈을 생성합니다.
ng g m modules/media

이렇게하면 폴더 media내부에 모듈이 생성됩니다 modules.

  1. 둘째,이 모듈에 추가 된 컴포넌트를 생성합니다
ng g c modules/media/picPick --module=modules/media/media.module.ts

명령의 첫 번째 부분은 새 모듈이 포함 된 내부 폴더 ng g c modules/media/picPick라는 구성 요소 폴더를 생성 합니다.picPickmodules/mediamedia

두 번째 부분은 모듈 파일에서 가져 와서이 모듈의 배열에 추가하여 모듈 picPick에서 새 컴포넌트를 선언 합니다.mediadeclarations

작업 트리

여기에 이미지 설명을 입력하십시오


2
이것이 어떻게 질문에 대답하는지 더 자세히 설명해 주시겠습니까?
— 스털링 궁수

참고해 주셔서 감사합니다. 나는 미래의 독자로서 답변을 편집했습니다 @CertainPerformance
— Elhakim

3

모듈 수준으로 이동 / 우리는 루트 수준에있을 수 있으며 아래 명령을 입력하십시오

ng g component "path to your component"/NEW_COMPONENT_NAME -m "MODULE_NAME"

예 :

ng g component common/signup/payment-processing/OnlinePayment -m pre-login.module

3

먼저 모듈을 생성하십시오.

ng g m moduleName --routing

그러면 moduleName 폴더가 생성되고 모듈 폴더로 이동합니다

cd moduleName

그런 다음 구성 요소를 생성합니다.

ng g c componentName --module=moduleName.module.ts --flat

모듈 폴더 안에 자식 폴더를 만들지 않으려면 --flat을 사용하십시오.


1

응용 프로그램의 여러 모듈과 비슷한 문제가 있습니다. 구성 요소는 모든 모듈에 작성 될 수 있으므로 구성 요소를 작성하기 전에 특정 모듈의 이름을 지정해야합니다.

'ng generate component newCompName --module= specify name of module'

1

이 간단한 명령을 사용하십시오 :

ng g c users/userlist

users: 모듈 이름.

userlist: 구성 요소 이름.


1

Angular 문서에 따르면 특정 모듈의 구성 요소를 만드는 방법은 다음과 같습니다.

ng g component <directory name>/<component name>

"directory name"= CLI가 기능 모듈을 생성 한 위치

예 :-

ng generate component customer-dashboard/CustomerDashboard

그러면 고객 대시 보드 폴더 내에 새 구성 요소의 폴더가 생성되고 CustomerDashboardComponent로 기능 모듈이 업데이트됩니다.


1

먼저 실행하십시오 ng g module newModule . 그런 다음 실행ng g component newModule/newModule --flat


1

특정 루트 폴더로 구성 요소 기반 하위 모듈을 만들었습니다.

내가 지정한 아래 cli 명령은 확인하십시오.

ng g c Repair/RepairHome -m Repair/repair.module

수리 는 우리 자식 모듈의 루트 폴더입니다

-m은-모듈입니다

compount를위한 c

생성을위한 g


1

Angular 9 응용 프로그램을 스캐 폴딩하는 동안 오늘이 문제가 발생했습니다. 내가 추가 할 때마다 "모듈에 오류가 존재하지 않습니다"가지고 .module.ts또는 .module모듈 이름. cli는 확장명이없는 모듈 이름 만 필요합니다. 내가 모듈 이름을 가지고 있다고 가정하면 : brands.module.ts내가 사용한 명령은

ng g c path/to/my/components/brands-component -m brands --dry-run

--dry-run파일 구조가 올바른지 확인한 후 제거 하십시오.


1

일반적인 패턴은 경로, 느리게로드 된 모듈 및 구성 요소로 피처를 작성하는 것입니다.

노선: myapp.com/feature

app-routing.module.ts

{ path: 'feature', loadChildren: () => import('./my-feature/my-feature.module').then(m => m.MyFeatureModule) },

파일 구조 :

app   
└───my-feature
│   │   my-feature-routing.module.ts
│   │   my-feature.component.html
│   │   my-feature.component.css
│   │   my-feature.component.spec.ts
│   │   my-feature.component.ts
│   │   my-feature.module.ts

이것은 다음과 같이 진료소에서 수행 할 수 있습니다.

ng generate module my-feature --module app.module --route feature

또는 더 짧은

ng g m my-feature --module app.module --route feature

또는 이름을 생략하면 클리닉에서 메시지를 표시합니다. 여러 기능을 만들어야 할 때 매우 유용

ng g m --module app.module --route feature

0

Angular CLI를 사용하여 Angular 4 앱에 컴포넌트 추가

앱에 새로운 Angular 4 컴포넌트를 추가하려면 command를 사용하십시오 ng g component componentName. 이 명령을 실행 한 후 Angular CLI는 component-name아래 에 폴더를 추가합니다 src\app. 또한 동일한 참조가 src\app\app.module.ts파일에 자동으로 추가 됩니다.

구성 요소에는 @Component데코레이터 기능 이 있어야하고 그 뒤에 에드가 class필요합니다 export. @Component장식 기능은 메타 데이터를 받아 들인다.

Angular CLI를 사용하여 Angular 4 앱의 특정 폴더에 구성 요소 추가

특정 폴더에 새 구성 요소를 추가하려면 다음 명령을 사용하십시오. ng g component folderName/componentName


0

.angular-cli.json에 선언 된 여러 개의 앱이있는 경우 (예 : 기능 모듈에서 작업하는 경우)

"apps": [{
    "name": "app-name",
    "root": "lib",
    "appRoot": ""
}, {...} ]

당신은 할 수 있습니다 :

ng g c my-comp -a app-name

-a는 --app (이름)를 나타냅니다.


0

이 특정 명령을 사용하여 모듈 내부에서 구성 요소를 생성합니다.

ng g c <module-directory-name>/<component-name>

이 명령은 모듈의 로컬 구성 요소를 생성합니다. 또는 먼저 입력하여 디렉토리를 변경할 수 있습니다.

cd <module-directory-name>

그런 다음 구성 요소를 작성하십시오.

ng g c <component-name>

참고 : <>로 묶인 코드는 사용자 별 이름을 나타냅니다.


0

평소와 같이 기능 모듈을 만듭니다.

ng generate module dirlevel1/module-name

2 .- 당신은 지정할 수 있습니다 루트 경로 에서 프로젝트의 --module (만 --module에서, (/) 루트 점을 당신에게 프로젝트 ROOT를 하고 시스템 루트지지 않습니다! )

ng generate component dirlevel1/component-name --module /src/app/dirlevel1/module-name.module.ts

실제 예 :

ng generate module stripe/payment-methods-list
ng generate component stripe/payment-methods-list --module=/src/app/stripe/payment-methods-list/payment-methods-list.module.ts 

산출:

CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.scss (0 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.html (39 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.spec.ts (768 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.ts (322 bytes)
UPDATE src/app/stripe/payment-methods-list/payment-methods-list.module.ts (311 bytes)
[OK] Generated component!

Angular CLI로 테스트 : 9.1.4


0
ng g c componentName --module=path-to-your-module-from-src-folder

예:

ng g c testComponent --module=/src/app/home/test-component/test-component.module

0

모듈, 서비스 및 구성 요소를 특정 모듈로 작성

Basic:

    ng g module chat     
    ng g service chat/chat -m chat
    ng g component chat/chat-dialog -m chat

    In chat.module.ts:
        exports: [ChatDialogComponent],
        providers: [ChatService]

    In app.module.ts:

        imports: [
            BrowserModule,
            ChatModule
        ]

    Now in app.component.html:
        <chat-dialog></chat-dialog>


LAZY LOADING:
    ng g module pages --module app.module --route pages

        CREATE src/app/pages/pages-routing.module.ts (340 bytes)
        CREATE src/app/pages/pages.module.ts (342 bytes)
        CREATE src/app/pages/pages.component.css (0 bytes)
        CREATE src/app/pages/pages.component.html (20 bytes)
        CREATE src/app/pages/pages.component.spec.ts (621 bytes)
        CREATE src/app/pages/pages.component.ts (271 bytes)
        UPDATE src/app/app-routing.module.ts (8611 bytes)       

    ng g module pages/forms --module pages/pages.module --route forms

        CREATE src/app/forms/forms-routing.module.ts (340 bytes)
        CREATE src/app/forms/forms.module.ts (342 bytes)
        CREATE src/app/forms/forms.component.css (0 bytes)
        CREATE src/app/forms/forms.component.html (20 bytes)
        CREATE src/app/forms/forms.component.spec.ts (621 bytes)
        CREATE src/app/forms/forms.component.ts (271 bytes)
        UPDATE src/app/pages/pages-routing.module.ts (437 bytes)
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.