IT story

Angular2 RC6 : '

hot-time 2020. 7. 30. 09:45
반응형

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

구성 요소를 찾을 수없는 이유를 모르겠습니다. 내 PlannerModule은 다음과 같습니다.

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

그리고 ng2의 모듈 개념을 이해하는 한 모듈의 일부는 '선언'으로 선언됩니다. 완전성을 위해 PlannerComponent는 다음과 같습니다.

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

및 HeaderAreaComponent :

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

<header-area>태그 지정은 planner.component.html에 있습니다 :

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

    <div class="row">...

내가 뭔가 잘못 받았 니?

업데이트 : 완전한 코드

planner.module.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 {
}

planner.component.html

<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에서 구성 요소를 사용하려고 할 때이 오류가 발생했습니다.

exports배열 에서 해당 구성 요소를 선언하는 문제였습니다 .

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

Sanket의 답변 과 의견 도움으로 문제를 해결했습니다 .

당신이 모르는 오류 메시지에 분명 아니었다 수있는 것은 : 내가 가져온 PlannerComponent을 A와 NgModule.declaration @ 내 응용 프로그램 모듈 (= RootModule)에서.

PlannerModule@ NgModule.imports가져 와서 오류가 수정되었습니다 .

전에:

@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 {
}

당신의 도움을 주셔서 감사합니다 :)


Webclipse가 자동으로 생성 한 컴포넌트 정의를 사용한 경우 선택기 이름 앞에 'app-'가 붙은 것을 알 수 있습니다. 분명히 이것은 주 앱 구성 요소의 하위 구성 요소를 선언 할 때 새로운 규칙입니다. 'new'- 'component'를 사용하여 Angular IDE에서 선택기를 사용한 경우 구성 요소에 선택기가 어떻게 정의되어 있는지 확인하십시오. 그래서 대신에

<header-area></header-area>

너는 필요할지도 모른다

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

당신의에서 플래너 구성 요소, 당신은 수입 실종해야 HeaderAreaComponent를 this-처럼

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

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

이것이 도움이되는지보십시오.


<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 : 이 메시지를 메시지 플래시 메시지에 사용하고 있습니다


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();
  }));
});

각도 RC.6에서 동일한 문제가 발생했습니다. 어떤 이유로 든 구성 요소를 지시어를 부모 구성 요소로 사용하여 다른 구성 요소로 전달할 수 없습니다

그러나 앱 모듈을 통해 자식 구성 요소를 가져 와서 선언 배열에 추가하면 오류가 사라집니다. 이것이 왜 각도 rc.6의 문제인지에 대한 설명이별로 없습니다.


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

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

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

나는이 문제가 있었을 때 나는 장식에 'templateUrl'대신에 단지 '템플릿'을 사용하기 때문에 내가 사용하기 때문에, 그것은이었다 웹팩 사용하고 필요를 필요로 그 안에. 데코레이터 이름에주의하십시오. 제 경우에는 스 니펫을 사용하여 상용구 코드를 생성했으며 데코레이터는 다음과 같이 생성되었습니다.

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

하지만 웹팩의 장식은 '해야 템플릿 ' NOT ' templateUrl 과 같이':

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

이것을 변경하면 문제가 해결되었습니다.

두 가지 방법에 대해 더 알고 싶습니까? 읽기 에 대한이 매체 포스트 template대를templateUrl


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

파일 이름 : list.component.ts

내 보낸 클래스 : ListStudentsComponent

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


나는이 정확한 문제를 겪었다. 실패 : 템플릿 구문 분석 오류 : '앱 로그인'알려진 요소 아니지만 ... 함께 ng test. 위의 모든 대답을 시도했습니다. 아무 효과가 없습니다.

NG 테스트 솔루션 :

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

<= 문제가되는 구성 요소에 대한 선언 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();
  ...

나는 같은 문제가 있었고 내 구성 요소가 선언 된 모듈 (ModuleLower)의 내보내기 배열에 구성 요소 (MyComponentToUse)를 추가하여 수정했습니다. 그런 다음 ModuleHigher에서 ModuleLower를 가져 오므로 이제 ModuleLower 및 ModuleHigher에서 내 컴포넌트 (MyComponentToUse)를 재사용 할 수 있습니다.

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


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

테스트 구성 요소를 선언하여 테스트 모듈을 다듬을 때 Angular 7과 동일한 문제가 발생했습니다. schemas: [ CUSTOM_ELEMENTS_SCHEMA ]다음과 같이 추가 하고 오류가 해결되었습니다.

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

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

app-root태그 된 index.html에 존재하지 않았다


OnInitng new ...각도 CLI 에서 핵심 문구를 사용하여 새 구성 요소를 생성하는 동안 클래스에서 자동으로 구현되었습니다 . 따라서 구현을 제거하고 생성 된 빈 메소드를 제거한 후에 문제가 해결되었습니다.


나를 위해 templateUrl의 경로 가 올바르지 않습니다

나는 사용하고 있었다

shopping-list-edit.component.html

그것이 있어야했던 반면

./shopping-list-edit.component.html

어리석은 실수이지만 시작할 때 발생합니다. 누군가 고통을 겪는 데 도움이되기를 바랍니다.


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

Ionic에서 사용자 지정 각도 구성 요소는이라는 별도의 모듈로 구성됩니다 ComponentsModule. 구성 요소와 함께을 사용하여 첫 번째 구성 요소를 생성하면 ionic generate componentionic은을 생성합니다 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 {}

To use the ComponentsModule in the app, like any other angular modules, the ComponentsModules needs to be imported to the AppModule. ionic generate component (v 4.12) does not add this step, so this has to be added manually.

Excerpt of 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 {}

For future problems. If you think you followed all the good answers and yet, the problem is there.

Try turning the server off and on.

I had the same problem, followed all the steps, couldn't solve it. Turn off, on and it was fixed.


Ok, let me give the details of code, how to use other module's component.

For example, I have M2 module, M2 module have comp23 component and comp2 component, Now I want to use comp23 and comp2 in app.module, here is how:

this is app.module.ts, see my comment,

 // 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 { }

this is m2 module:

   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 { }

My commend in code explain what you need to do here.

now in app.component.html, you can use

  <app-comp23></app-comp23>

follow angular doc sample import modul

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

반응형