CUSTOM_ELEMENTS_SCHEMA가 NgModule.schemas에 추가되어 여전히 오류가 표시됨


137

방금 Angular 2 rc4에서 rc6으로 업그레이드하여 문제가 발생했습니다.

콘솔에 다음 오류가 표시됩니다.

Unhandled Promise rejection: Template parse errors:
'cl-header' is not a known element:
1. If 'cl-header' is an Angular component, then verify that it is part of this module.
2. If 'cl-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("<main>
    [ERROR ->]<cl-header>Loading Header...</cl-header>
    <div class="container-fluid">
      <cl-feedbackcontai"): AppComponent@1:4

내 헤더 구성 요소는 다음과 같습니다.

import { Component } from '@angular/core';
import { Router } from '@angular/router';

// own service
import { AuthenticationService } from '../../../services/authentication/authentication.service.ts';

import '../../../../../public/css/styles.css';

@Component({
  selector: 'cl-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent { // more code here... }

여기 내 헤더 모듈이 있습니다 :

import { NgModule, CUSTOM_ELEMENTS_SCHEMA }      from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule }      from '@angular/common';
import { FormsModule }      from '@angular/forms';

import { HeaderComponent }  from './../../../components/util_components/header/header.component.ts';

@NgModule({
    declarations: [ HeaderComponent ],
    bootstrap:    [ HeaderComponent ],
    imports: [ RouterModule, CommonModule, FormsModule ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class HeaderModule { }

HeaderModule을 가져 오는 util 모듈이라는 래퍼 모듈을 만들었습니다.

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

import {HeaderModule} from "./header/header.module";
// ...

@NgModule({
    declarations: [ ],
    bootstrap:    [ ],
    imports: [ HeaderModule]
})
export class UtilModule { }

마지막으로 AppModule에서 가져옵니다.

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

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

import {UtilModule} from "./modules/util_modules/util.module";
import {RoutingModule} from "./modules/routing_modules/routing.module";

@NgModule({
    bootstrap: [AppComponent],
    declarations: [AppComponent],
    imports: [BrowserModule, UtilModule, RoutingModule]
})
export class AppModule { }

내 이해를 위해 SCHEMA를 사용하여 오류 메시지의 지시를 따라 오류를 억제하고 있습니다. 그러나 작동하지 않는 것 같습니다. 내가 뭘 잘못하고 있죠? (저는 지금 보지 못하는 것이 분명하지 않기를 바랍니다. 지난 6 시간 동안이 버전으로 업그레이드했습니다 ...)


1
당신이 그것을 추가 AppModule하면 여전히 구성 요소에 추가해야합니까?
— Alessandro Resta

1
"스키마 : [CUSTOM_ELEMENTS_SCHEMA]"만 추가하면 매력처럼 작동했습니다. 감사합니다 :)
— AIon

3
"Fix"를이 질문에 대한 답변으로 추가하면 도움이 될 것입니다. 따라서 귀하의 질문에 답하는 다른 사람들이 귀하의 솔루션을 사용하여 어떻게 혜택을 얻을 수 있는지 정확히 알 수 있습니다.]
— Danny Bullis

답변:


97

이것에 조금 더 추가하고 싶었습니다.

새로운 앵귤러 2.0.0 최종 릴리스 (2016 년 9 월 14 일)에서 사용자 정의 html 태그를 사용하는 경우이를보고합니다 Template parse errors. 맞춤 태그는 이러한 태그 중 하나가 아닌 HTML에서 사용 하는 태그 입니다.

schemas: [ CUSTOM_ELEMENTS_SCHEMA ]사용자 정의 HTML 태그를 사용하는 각 구성 요소에 행 을 추가해야합니다.

편집 :schemas 선언은에 있어야 @NgModule장식. 아래 예제 CustomComponent는 하나의 컴포넌트에 대한 html 템플리트의 html 태그를 허용 하는 사용자 정의 컴포넌트가있는 사용자 정의 모듈을 보여줍니다 .

custom.module.ts

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

import { CustomComponent } from './custom.component';

@NgModule({
  declarations: [ CustomComponent ],
  exports: [ CustomComponent ],
  imports: [ CommonModule ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class CustomModule {}

custom.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-custom-component',
  templateUrl: 'custom.component.html'
})
export class CustomComponent implements OnInit {
  constructor () {}
  ngOnInit () {}
}

custom.component.html

여기에서 원하는 HTML 태그를 사용할 수 있습니다.

<div class="container">
  <boogey-man></boogey-man>
  <my-minion class="one-eyed">
    <job class="plumber"></job>
  </my-minion>
</div>

단일 모듈에 여러 구성 요소가있는 매우 간단한 앱이 있습니다. 모듈에 추가했습니다 ... 여전히 오류가 발생합니다 ...
— Nicolas Irisarri

7
고마워 칼렙. 간단한 테스트를 실행할 때 오류가 발생했습니다. 나는 그것을 알아 냈습니다 ... 나는 CUSTOM_ELEMENTS_SCHEMA단위 테스트 가짜 모듈에 추가하지 않았습니다 . 내가 그렇게하자마자 불평이 멈추었습니다.
— Nicolas Irisarri

1
허용되는 사용자 정의 요소를 정의하는 방법이 있습니까? 를 사용하면 CUSTOM_ELEMENTS_SCHEMA찾기 어려운 오류가 발생할 수 있지만, ng-content특정 요소 이름없이 오류를 발생시키고 구성 요소를 만들지 않고 컨트롤의 섹션에 사용자 지정 요소 이름을 사용 하고 싶습니다.
— Jason Goemaat

1
@ Caleb 당신이 의미하는 바에 대한 간단한 코드 예제를 제공 할 수 있습니까? HTML 태그를 사용하는 각 구성 요소에 줄 schemas: [ CUSTOM_ELEMENTS_SCHEMA ]을 추가 해야하는 것처럼 보입니다 . Component데코레이터가 schemas매개 변수를 허용하지 않는 것 같습니다 .
— Danny Bullis

2
@DannyBullis는 Component데코레이터 대신 데코레이터에서 찾을 수 NgModule있습니다. 해당 구성 요소에 대한 모듈을 만든 다음 스키마를 지정할 수 있습니다. 문서와 예제에 연결하십시오.
— Caleb

85

이것은 다음에 의해 수정됩니다.

a) schemas: [ CUSTOM_ELEMENTS_SCHEMA ]모든 구성 요소에 추가 또는

b) 추가

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

과

schemas: [
  CUSTOM_ELEMENTS_SCHEMA
],

모듈에.


7
선언하는 것을 잊지 마십시오 ... @ angular / core에 있습니다. 그와 같은 것이 적합해야합니다 :import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
— rlasjunies

이 게시물은 다음 절차에 도움이 될 수 있습니다. medium.com/google-developer-experts/…
— Carlos E

1
[CUSTOM_ELEMENTS_SCHEMA] 스키마를 모든 구성 요소에 추가하면 트릭을 수행했습니다! 감사!
— Pedro Ferreira

각도 9에 스키마가 존재하지 않음
— Renil Babu

37

사용자 지정 요소를 사용하여 구성 요소를 테스트하는 경우 단위 테스트를 실행할 때 발생할 수도 있습니다. 이 경우 해당 구성 요소의 .spec.ts 파일 시작 부분에서 설정을 가져 오는 testingModule에 custom_elements_schema를 추가해야합니다. header.component.spec.ts 설정이 시작되는 방법의 예는 다음과 같습니다.

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

describe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [PrizeAddComponent],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA
      ],
    })
      .compileComponents();
  }));

1
감사! 이것을 찾기 위해 너무 오랫동안 # & @ % 나왔습니다.
— eflat

23

@NgModule({})'app.module.ts'에 다음을 추가하십시오 .

import {CUSTOM_ELEMENTS_SCHEMA} from `@angular/core`;

그리고

schemas: [
    CUSTOM_ELEMENTS_SCHEMA
]

'app.module.ts'는 다음과 같아야합니다.

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [],
  imports: [],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

2
하지만 이제는 전체 앱에서 맞춤 태그를 허용하고 있습니다.
— EE33

10

그것은 나에게도 효과가 없었다. 나는 바꿨다

CUSTOM_ELEMENTS_SCHEMA

...에 대한

NO_ERRORS_SCHEMA

이 기사에서 제안 된 것은 https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

이제 작동합니다.


좋은! 그것은 나를 위해 일했다. 구성 요소 HTML에 XML 요소를 추가하고 싶었고 오류가 발생했습니다. 고마워요
— 셀소 소아레스

각도 요소 (Angular 8) 내의 각도 요소 내에서 각도 요소를 제공하는 CUSTOM_ELEMENTS_SCHEMA것이 도움이되지는 않았지만 NO_ERRORS_SCHEMA트릭을 수행했으며 독립형 각도 요소의 모든 중첩은 이제 매력처럼 작동합니다.
— Yogi

이것은 나를 위해 일했습니다 TestBed. 요소가 제대로 작동했지만 테스트에 실패했습니다. 추가 schemas: [NO_ERRORS_SCHEMA]하고 모두 좋습니다.
— VSO

9

util.component.ts

@Component({
    selector: 'app-logout',
    template: `<button class="btn btn-primary"(click)="logout()">Logout</button>`
})
export class LogoutComponent{}

util.module.ts

@NgModule({
    imports: [...],
    exports: [
        LogoutComponent
    ],
    declarations: [LogoutComponent]
})
export class AccountModule{};

LogoutComponent를 내 보내야합니다

'util.module'에서 import {AccountModule} 을 사용하려는 모듈에서 dashboard.module.ts
가져 오기AccountModule<app-logout> ;

@NgModule({
  imports: [
    CommonModule, AccountModule
  ],
  declarations: [DashboardComponent]
})
export class DashboardModule { }

dashboard.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  template: `<div><app-logout></app-logout></div>`
})
export class DashboardComponent implements OnInit {
  constructor() {}
  ngOnInit() {}
}

가져 와서 사용할 필요는 없습니다 CUSTOM_ELEMENTS_SCHEMA.
그러나 dashboard.module이 느리게로드되면 작동하지 않습니다. 지연 로딩의 경우에
사용하면 CUSTOM_ELEMENTS_SCHEMA오류가 억제되지만 구성 요소는 dom에 추가되지 않습니다.


idem +1 더 이상 오류는 없지만 더 이상 dom 업데이트가 없습니다. '-'를 사용하여 해당 선택자를 작업하려고 시도하는이 해결 방법은 #### !!! && ù * $
— user1568220

1
고마워요, 일주일 후, 나는 이온에서 게으른 로딩과 함께 작동 할 수 없다는 것을 알았습니다.
— Amr.Ayoub

1
@Arun-솔루션이 100 % 정확합니다. 1) 내보내기에 추가 할 필요가 있고 2) custom_elements_schema가 필요하지 않습니다
— Ashwin

나는 같은 오류가 있었고 선언 클래스에서 필요한 각 모듈에 구성 요소를 설정했습니다. CUSTOM_ELEMENTS_SCHEMA를 사용하지 않았고 일했습니다.
— David

6

Angular Material을 포함하는 구성 요소에서도 비슷한 단위 오류가 발생했습니다. 위의 @ Dan Stirling-Talbert의 답변에 따라이를 내 구성 요소 .spec 파일에 추가하고 오류가 단위 테스트에서 지워졌습니다.

Import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'

그런 다음 생성 된 beforeEach () 문에 스키마를 추가하십시오.

beforeEach(asyn(() => {
    declarations: [ AboutComponent ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));

내 카르마 오류는 'mat-panel-title'이 웹 구성 요소 인 경우이 메시지를 표시하지 않으려면이 구성 요소의 '@ NgModule.schemas'에 'CUSTOM_ELEMENTS_SCHEMA'를 추가하십시오.


4

이 게시물을 읽고 각도 2 문서에 따르면 :

export CUSTOM_ELEMENTS_SCHEMA
Defines a schema that will allow:

any non-Angular elements with a - in their name,
any properties on elements with a - in their name which is the common rule for custom elements.

CUSTOM_ELEMENTS_SCHEMA를 NgModule에 추가하고 나면 사용하는 새로운 커스텀 요소에 이름에 '대시'가 있는지 확인하십시오. 등


1
이름에 대시? 왜 그런 멍청한 협약을 강요합니까?
— Meryan

Ionic3에서 지연 로딩을 사용하기 시작했을 때와 웹용으로 빌드하려고 할 때만이 문제가 발생합니다. 언급 한 문서에 대한 링크를 게시 할 수 있습니다. 감사합니다.
— Meryan

3

이것은 다소 긴 글이며 문제에 대한 자세한 설명을 제공합니다.

다중 슬롯 컨텐츠 투영 이있을 때 문제가 발생합니다 (제 경우).

자세한 내용은 콘텐츠 프로젝션 도 참조하십시오 .

예를 들어 다음과 같은 구성 요소가있는 경우 :

html 파일 :

 <div>
  <span>
    <ng-content select="my-component-header">
      <!-- optional header slot here -->
    </ng-content>
  </span>

  <div class="my-component-content">
    <ng-content>
      <!-- content slot here -->
    </ng-content>
  </div>
</div>

TS 파일 :

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
})
export class MyComponent {    
}

그리고 당신은 그것을 다음과 같이 사용하고 싶습니다 :

<my-component>
  <my-component-header>
    <!-- this is optional --> 
    <p>html content here</p>
  </my-component-header>


  <p>blabla content</p>
  <!-- other html -->
</my-component>

그런 다음 알려진 Angular 구성 요소가 아닌 템플릿 구문 분석 오류가 발생하지만 실제로는 그렇지 않습니다. 구성 요소의 ng 내용에 대한 참조 일뿐입니다.

그리고 가장 간단한 수정은

schemas: [
    CUSTOM_ELEMENTS_SCHEMA
],

... app.module.ts에


그러나이 문제에 대한 쉽고 깨끗한 접근 방식이 있습니다- <my-component-header>슬롯에 HTML을 삽입하는 대신 사용하면 다음과 같이이 작업에 클래스 이름을 사용할 수 있습니다.

html 파일 :

 <div>
  <span>
    <ng-content select=".my-component-header">  // <--- Look Here :)
      <!-- optional header slot here -->
    </ng-content>
  </span>

  <div class="my-component-content">
    <ng-content>
      <!-- content slot here -->
    </ng-content>
  </div>
</div>

그리고 당신은 그것을 다음과 같이 사용하고 싶습니다 :

<my-component>
  <span class="my-component-header">  // <--- Look Here :) 
     <!-- this is optional --> 
    <p>html content here</p>
  </span>


  <p>blabla content</p>
  <!-- other html -->
</my-component>

따라서 ... 더 이상 존재하지 않는 구성 요소가 없으므로 app.module.ts에서 CUSTOM_ELEMENTS_SCHEMA가 필요하지 않으며 오류가 없으며 문제가 없습니다.

따라서 당신이 나와 같고 CUSTOM_ELEMENTS_SCHEMA를 모듈에 추가하고 싶지 않은 경우-이 방법으로 구성 요소를 사용하면 오류가 발생하지 않으며 더 분명합니다.

이 문제에 대한 자세한 내용은 https://github.com/angular/angular/issues/11251

각도 콘텐츠 프로젝션에 대한 자세한 정보-https: //blog.angular-university.io/angular-ng-content/

당신은 또한 https://scotch.io/tutorials/angular-2-transclusion-using-ng-content를 볼 수 있습니다


1
이것은 내가 찾던 것이 었습니다. 공유해 주셔서 감사합니다!
— romeouald

1

위의 답변이 내 오류를 완전히 수정하지 못했기 때문에 정보를 하나 더 추가하고 싶습니다.

내 시나리오에는 자식 구성 요소를 보유하는 부모 구성 요소가 있습니다. 그리고 그 하위 구성 요소에도 다른 구성 요소가 포함되어 있습니다.

따라서 부모 구성 요소의 사양 파일에는 자식 구성 요소 선언이 있어야합니다. 자녀의 자식 구성 요소입니다. 마침내 문제가 해결되었습니다.


1

사용자 정의 모듈을 사용하고 있다고 생각합니다. 다음을 시도해보십시오. your-module.module.ts 파일에 다음을 추가 해야합니다 .

import { GridModule } from '@progress/kendo-angular-grid';
@NgModule({
  declarations: [ ],
  imports: [ CommonModule, GridModule ],
  exports: [ ],
})

0

그것은 나를 위해 작동하지 않았습니다 (2.0.0 사용). 나를 위해 일한 것은 대신 RouterTestingModule을 가져 오는 것입니다.

사양 파일에서 RouterTestingModule을 가져 와서이 문제를 해결했습니다.

import {
    RouterTestingModule
} from '@angular/router/testing';

  beforeEach(() => {

        TestBed.configureTestingModule({
            providers: [
                App,
                AppState,
                Renderer,
                {provide: Router,  useClass: MockRouter }
            ],
            imports: [ RouterTestingModule ]
        });

    });

0

나를 위해, 나는 볼 필요가 있었다 :

1. If 'cl-header' is an Angular component, then verify that it is part of this module.

즉, 구성 요소가에 포함되어 있지 않습니다 app.module.ts. 가져 와서 declarations섹션에 포함되어 있는지 확인하십시오 .

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

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

import { UtilModule } from "./modules/util_modules/util.module";
import { RoutingModule } from "./modules/routing_modules/routing.module";

import { HeaderComponent } from "./app/components/header.component";

@NgModule({
    bootstrap: [AppComponent],
    declarations: [
        AppComponent,
        HeaderComponent
    ],
    imports: [BrowserModule, UtilModule, RoutingModule]
})
export class AppModule { }

0

방금 가져 와서 ClarityModule모든 문제를 해결했습니다. 시도 해봐!

import { ClarityModule } from 'clarity-angular';

또한 가져 오기에 모듈을 포함 시키십시오.

imports: [ ClarityModule ],


안녕하세요, Ishani. 왜 작동하는지 설명을 추가해 주시겠습니까?
— f.khantsis

우리가 설명서를 방문하는 경우 CUSTOM_ELEMENTS_SCHEMA에서 angular.io/api/core/CUSTOM_ELEMENTS_SCHEMA (-) {이 시나리오와 유사} 우리는 CUSTOM_ELEMENTS_SCHEMA가 NgModule 대시 케이스가 아닌 각도 요소를 포함 할 수 있습니다 찾을 수 있습니다. 가져올 때 선명도 모듈에는 기본적으로 모든 clr 아이콘 등이 포함되며 다른 명확성 모듈 기능도 사용할 수 있습니다.
— Ishani

이것은 여기서 문제와 관련이 없습니다. 선명도 모듈을 가져 와서 어떻게 해결합니까 ?? @Ishani
— HelloWorld

문제 설명을 읽으면 Angular는을 식별 할 수 없습니다 clr-header. 같은 오류가 발생 clr-icon합니다. 이전 의견에서 언급했듯이 Clarity 모듈에는 기본적으로 이러한 내용이 포함되어 있습니다. 귀하의 질문에 대한 답변이 되었기를 바랍니다.
— Ishani

0

/app/app.module.ts 파일에서이 문제를 해결했습니다.

컴포넌트를 가져 와서 선언하십시오

import { MyComponent } from './home-about-me/my.component';

@NgModule({
  declarations: [
    MyComponent,
  ]

-3

웹팩을 사용하셨습니까? 그렇다면, 설치하십시오

angular2-template-loader

그리고 넣어

test: /\.ts$/,
   loaders: ['awesome-typescript-loader', 'angular2-template-loader']

ng g에 의해 생성 된 구성 요소로 생성 된 동일한 기본 테스트를 경로로 지정할 수 없습니다. 내가 :( 부품 사양 파일을 주석 처리했을 때이 주제에서 아무것도 도움이 :( 나는 단지 오류를하지 않았다
— Nesquik27

맞춤 태그가 v2 이하의 각도에서만 작동한다는 것을 잘 알고 있습니까?! 나는 유튜브에서 뭔가를 확인하고 v4 환경에서 v2에서 내 코드를 테스트하려고합니다
— Nesquik27
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.