codememo

Angular2 RC6: '은(는) 알려진 요소가 아닙니다.'

tipmemo 2023. 5. 8. 22:16
반응형

Angular2 RC6: '은(는) 알려진 요소가 아닙니다.'

Angular 2 RC6 앱을 실행하려고 할 때 브라우저 콘솔에서 다음 오류가 발생합니다.

> Error: Template parse errors: 'header-area' is not a known element:
> 1. If 'header-area' is an Angular component, then verify that it is part of this module.
> 2. If 'header-area' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component
> to suppress this message.("

    <div class="page-container">
        [ERROR->]<header-area></header-area>
        <div class="container-fluid">

> "): PlannerComponent@1:2

나는 왜 부품이 발견되지 않는지 이해할 수 없습니다.내 플래너 모듈은 다음과 같습니다.

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
    ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
    ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {}

그리고 모듈 2의 개념을 이해한 바로는 모듈의 부품은 '선언'으로 선언되어 있습니다.완전성을 위해 Planner 구성요소는 다음과 같습니다.

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}

및 헤더 영역 구성요소:

@Component({
  selector: 'header-area',
  templateUrl: './header-area.component.html',
  styleUrls: ['./header-area.component.styl']
})
export default class HeaderAreaComponent {
}

<header-area>는 plannerplanner.component.html에 있습니다.

<div class="page-container">
  <header-area></header-area>
  <div class="container-fluid">

    <div class="row">...

제가 뭔가 잘못 이해했나요?

업데이트: 전체 코드

planner.sv.ts:

import HeaderAreaComponent from '../header-area/header-area.component';
import NavbarAreaComponent from '../navbar-area/navbar-area.component';
import GraphAreaComponent from '../graph-area/graph-area.component';
import EreignisbarAreaComponent from '../ereignisbar-area/ereignisbar-area.component';
import PlannerComponent from './planner.component';
import {NgModule} from '@angular/core';
import {nvD3} from 'ng2-nvd3';
import {RouterModule} from '@angular/router';
import {CommonModule} from '@angular/common';
import {ModalModule} from 'ng2-bootstrap/ng2-bootstrap';

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
  ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
  ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {
  // TODO: get rid of the "unused class" warning
}

planner.component.ts

import {Component} from '@angular/core';
import CalculationService from '../_shared/services/calculation.service/calculation.service';
import HeaderAreaComponent from '../header-area/header-area.component';

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}

플래너.구성요소.구성요소

<div class="page-container">
  <header-area></header-area>
  <div class="container-fluid">

    <div class="row">
      <div class="col-xs-2 col-sm-1 sidebar">
        <navbar-area></navbar-area>
      </div>
      <div class="col-xs-10 col-sm-11">
        <graph-area></graph-area>
      </div>
    </div><!--/.row-->

    <div class="row">
      <div class="col-xs-10 col-sm-11 offset-sm-1">
        <ereignisbar-area></ereignisbar-area>
      </div>
    </div><!--/.row-->

  </div><!--/.container-->
</div><!--/.page-container-->

모듈 A를 모듈 B로 가져온 다음 모듈 B의 모듈 A에서 구성 요소를 사용하려고 할 때 이 오류가 발생했습니다.

은 솔션은해요다선것입다니언에 해당 입니다.exportsvmdk

@NgModule({
  declarations: [
    MyComponent
  ],
  exports: [
    MyComponent
  ]
})
export class ModuleA {}
@NgModule({
  imports: [
    ModuleA
  ]
})
export class ModuleB {}

Sanket의 답변과 댓글을 참고하여 수정하였습니다.

오류 메시지에서 알 수 없거나 알 수 없는 것은 PlannerComponent를 AppModule(= 루트 모듈)에서 @NgModule.declaration으로 가져왔습니다.

PlannerModule as @NgModule.im 포트를 가져와 오류가 해결되었습니다.

이전:

@NgModule({
  declarations: [
    AppComponent,
    PlannerComponent,
    ProfilAreaComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    GraphAreaComponent,
    EreignisbarAreaComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routeConfig),
    PlannerModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {

이후:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routeConfig),
    PlannerModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

도와주셔서 감사합니다 :)

Webclip 자동 생성 구성 요소 정의를 사용한 경우 선택기 이름 앞에 'app-'이 추가되어 있을 수 있습니다.보아하니 이것은 주요 앱 구성 요소의 하위 구성 요소를 선언할 때의 새로운 관례입니다.'new' - 'component'를 사용하여 Angular IDE로 작성한 경우 구성 요소에서 선택기가 어떻게 정의되었는지 확인하십시오. 따라서 입력하는 대신

<header-area></header-area>

필요할 수도 있습니다.

<app-header-area></app-header-area>

에 대해서도 같은 문제가 발생합니다.<flash-messages></flash-messages>각이 5인

app.module.ts 파일에 아래 행을 추가하기만 하면 됩니다.

import { ---, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FlashMessageModule } from "angular-flash-message";


@NgModule({
  ---------------
  imports: [
    FlashMessageModule,
    ------------------         
  ], 
  -----------------
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
  ------------
})

NB: 메시지 플래시 메시지에 사용합니다.

플래너 구성 요소에서 헤더 영역 구성 요소 가져오기가 누락된 것이 분명합니다.

import { HeaderAreaComponent } from '../header-area.component'; 
//change path according your project

또한 모든 구성 요소 파이프는 NgModule을 통해 선언되어야 합니다.

이게 도움이 되는지 보세요.

Angular 7에서 이 문제에 직면했는데 모듈을 만든 후에 수행하지 않은 것이 문제였습니다.ng build그래서 공연을 했습니다.

  • ng build
  • ng serve

그리고 그것은 성공하였다.

구성 요소가 없을 때 단위 테스트에서 오류가 발생합니다.<router-outlet>.따라서 아래와 같이 테스트 파일에 구성 요소를 정의해야 합니다.

<app-header></app-header>
<router-outlet></router-outlet>

그런 다음 아래와 같이 spec.ts 파일을 추가해야 합니다.

import { HeaderComponent } from './header/header.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        App`enter code here`Component,
        HeaderComponent <------------------------
      ],
    }).compileComponents();
  }));
});

동일한 문제가 발생하여 구성 요소가 선언된 모듈(ModuleLower)의 내보내기 배열에 구성 요소(MyComponentToUse)를 추가하여 수정했습니다.그런 다음 모듈을 모듈 아래로 가져옵니다.Higher. 이제 모듈 하부 및 모듈에서 내 구성 요소(사용할 구성 요소)를 재사용할 수 있습니다.더 높은

            @NgModule({
              declarations: [
                MyComponentToUse
              ],
              exports: [
                MyComponentToUse
              ]
            })
            export class ModuleLower {}


            @NgModule({
              imports: [
                ModuleLower
              ]
            })
            export class ModuleHigher {} 

동일한 오류 메시지가 표시되는 또 다른 원인은 태그 이름과 선택기 이름이 일치하지 않는 경우입니다.이 경우:

<header-area></header-area>은 태그이정일치합야니다해확히이름과 정확히 .'header-area'구성 요소 선언에서:

@Component({
  selector: 'header-area',

저는 앵귤러 RC.6에서도 동일한 문제가 있었습니다. 어떤 이유에서인지 부모 구성요소에 대한 지시사항을 사용하여 구성요소를 다른 구성요소로 전달하는 것이 허용되지 않습니다.

하지만 앱 모듈을 통해 하위 구성 요소를 가져와서 선언 배열에 추가하면 오류가 사라집니다.이것이 왜 각도 rc.6의 문제인지에 대한 설명은 많지 않습니다.

제가 이 문제를 겪었을 때, 는 웹팩을 사용하고 있고 require를 사용해야 하기 때문에 데코레이터에서 단순히 'templateUrl'이 아닌 'templateUrl'을 사용했기 때문입니다.장식가 이름만 주의하면 됩니다. 제 경우에는 스니펫을 사용하여 보일러 플레이트 코드를 생성했습니다. 장식가는 다음과 같이 생성되었습니다.

@Component({
  selector: '',
  templateUrl: 'PATH_TO_TEMPLATE'
})

그러나 웹 팩의 경우 데코레이터는 다음과 같이 'templateUrl'이 아니라 'template'여야 합니다.

@Component({
  selector: '',
  template: require('PATH_TO_TEMPLATE')
})

이것을 바꾸는 것은 저에게 문제를 해결했습니다.

두 가지 방법에 대해 더 알고 싶습니까?이 중간 게시물을 읽어 보십시오.

파일 이름과 클래스 내보내기 불일치가 있을 때 다음 오류가 발생했습니다.

파일 이름: list.component.ts

내보낸 클래스:학생 나열 구성 요소

ListStudentsComponent에서 ListComponent로 변경하여 문제가 해결되었습니다.

저는 이 정확한 문제를 우연히 발견했습니다.실패: 템플릿 구문 분석 오류: 'app-login'은(는) 알려진 요소가 아닙니다.와 함께ng test위의 답변을 모두 시도해 보았습니다. 아무 것도 작동하지 않았습니다.

NG 테스트 솔루션:

Angular 2 Karma 테스트 'component-name'은(는) 알려진 요소가 아닙니다.

구성 요소에 대한 선언을 <= 대추다다니습가했음에선언을한요소구되에성는문제가▁<▁intoending▁declar▁compon▁offations▁for>에 추가했습니다.beforEach(.. declarations[])app.component.spec.ts에 연결합니다.

예제 app.component.spec.ts

...
import { LoginComponent } from './login/login.component';
...
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ...
      ],
      declarations: [
        AppComponent,
        LoginComponent
      ],
    }).compileComponents();
  ...

미래의 문제를 위해.만약 여러분이 모든 좋은 답을 따랐다고 생각한다면, 문제는 거기에 있습니다.

서버를 껐다가 다시 켜 보십시오.

저도 같은 문제를 겪었고, 모든 단계를 따라갔지만, 해결할 수 없었습니다.꺼, 꺼, 켜, 고쳤어요.

인적 오류 - 오류 메시지에 현혹되지 마십시오.

내가 현혹된 이유:사용하고자 하는 구성 요소(A 구성 요소)가 해당 모듈(A 모듈)에 올바르게 선언되었습니다.그것은 그곳에서도 올바르게 수출되었습니다.제가 작업하고 있는 구성요소(구성요소 B)의 모듈(모듈 B)은 모듈 A에 대한 가져오기가 올바르게 지정되었습니다.그러나 <component-a-selector > is not known element'라는 오류 메시지 때문에 모듈 A/Component A에 문제가 있다고 생각하는 데 집중했습니다. 오류 메시지에 포함된 내용이기 때문입니다. 사용하려는 구성 요소를 살펴볼 생각은 없었습니다.저는 이에 대한 모든 위협의 모든 게시물을 추적했지만 결국 중요한 단계를 놓치고 있었습니다.

문제를 해결한 이유: frot.io 의 답변으로 app.sys.ts 가져오기 목록을 확인하게 되었고 작업 중인 구성 요소(ComponentB)가 포함되지 않았습니다!

제 경우에도 초보자의 실수로 동일한 오류 메시지가 생성되었습니다.

app-root태그가 인덱스에 없습니다.

templateUrl에 대한 경로가 올바르지 않습니다.

사용하고 있었습니다.

shopping-list-edit.component.message

반면에 그것은 그랬어야만 했습니다.

./syslog-list-edit.component.vmdk

바보 같은 실수지만 시작할 때 발생합니다.곤경에 처한 누군가를 돕는 희망.

테스트 구성 요소를 선언하여 테스트 모듈을 개선하려고 할 때 Angular 7에서도 동일한 문제가 있었습니다.방금 추가됨schemas: [ CUSTOM_ELEMENTS_SCHEMA ]다음과 같이 오류가 해결되었습니다.

TestBed.configureTestingModule({
  imports: [ReactiveFormsModule, FormsModule],
  declarations: [AddNewRestaurantComponent],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
});

한 모듈에서 구성 요소를 선언하고 이를 내보낸 다음 다른 모듈에서 사용하는 경우 내보낸 모듈도 앱 모듈로 가져오는지 확인해야 합니다.:)

OnInit사용하는 동안 내 수업에 자동으로 구현되었습니다.ng new ...새 구성 요소를 생성할 각 CLI의 키 구문입니다.따라서 구현을 제거하고 생성된 빈 메서드를 제거한 후 문제가 해결됩니다.

네, 코드에 대한 자세한 내용, 다른 모듈의 구성 요소 사용 방법을 알려드리겠습니다.

예를 들어, 저는 M2 모듈을 가지고 있고, M2 모듈은 comp23 구성 요소와 comp2 구성 요소를 가지고 있습니다. 이제 저는 app.module에서 comp23과 comp2를 사용하고 싶습니다. 방법은 다음과 같습니다.

이것은 app.vmdk.ts입니다, 제 댓글을 보세요.

 // import this module's ALL component, but not other module's component, only this module
  import { AppComponent } from './app.component';
  import { Comp1Component } from './comp1/comp1.component';

  // import all other module,
 import { SwModule } from './sw/sw.module';
 import { Sw1Module } from './sw1/sw1.module';
 import { M2Module } from './m2/m2.module';

   import { CustomerDashboardModule } from './customer-dashboard/customer-dashboard.module';


 @NgModule({

    // declare only this module's all component, not other module component.  

declarations: [
AppComponent,
Comp1Component,


 ],

 // imports all other module only.
imports: [
BrowserModule,
SwModule,
Sw1Module,
M2Module,
CustomerDashboardModule // add the feature module here
],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

이것은 m2 모듈입니다.

   import { NgModule } from '@angular/core';
   import { CommonModule } from '@angular/common';

   // must import this module's all component file
   import { Comp2Component } from './comp2/comp2.component';
   import { Comp23Component } from './comp23/comp23.component';

   @NgModule({

   // import all other module here.
     imports: [
       CommonModule
     ],

    // declare only this module's child component. 
     declarations: [Comp2Component, Comp23Component],

   // for other module to use these component, must exports
     exports: [Comp2Component, Comp23Component]
   })
   export class M2Module { }

당신이 여기서 무엇을 해야 하는지를 코드로 설명합니다.

이제 app.component.dll에서 사용할 수 있습니다.

  <app-comp23></app-comp23>

follow angledoc 샘플 가져오기 모듈

스레드에 대한 답변은 늦었지만, 다른 관점에서 설명한 이 정보를 사용할 수 있는 사람들이 더 많을 것이라고 확신합니다.

은 이오니아 서사용정의각도에구성다요소음다구성니됩아모래듈에같별은도의과는자▁▁in▁separate다▁angular▁compon에▁under▁organized▁custom▁ionic▁a니ents▁are구라고 하는 별도의 모듈 아래에 구성됩니다.ComponentsModule 구성요소가 사첫을여번구때요생을 사용하여 될 때ionic generate component 물질은 γγος γος γος γος γος를 합니다.ComponentsModule이후의 모든 구성 요소는 동일한 모듈에 추가됩니다.

여기 샘플이 있습니다.ComponentsModule

import { NgModule } from '@angular/core';
import { CustomAngularComponent } from './custom/custom-angular-component';
import { IonicModule } from 'ionic-angular';
@NgModule({
    declarations: [CustomAngularComponent],
    imports: [IonicModule],
    exports: [CustomAngularComponent],
    entryComponents:[

      ]
})
export class ComponentsModule {}

용방법을 ComponentsModule모듈과 로 에서앱, 각모듈럼처도,ComponentsModules를 에가와합다로 합니다.AppModule이온 생성 구성 요소(v4.12)는 이 단계를 추가하지 않으므로 수동으로 추가해야 합니다.

AppModule 발췌:

@NgModule({
  declarations: [
    //declaration
  ],
  imports: [
    //other modules 
    ComponentsModule,
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    //ionic pages
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    //other providers
  ]
})
export class AppModule {}

언급URL : https://stackoverflow.com/questions/39333739/angular2-rc6-component-is-not-a-known-element

반응형