Programming

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

procodes 2020. 7. 23. 21:07
반응형

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


방금 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 시간 동안이 버전으로 업그레이드했습니다 ...)


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

새로운 앵귤러 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>

이봐,이 수정하여 해결

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

b) 추가

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

schemas: [
    CUSTOM_ELEMENTS_SCHEMA
],

모듈에.

건배, 라파엘


사용자 지정 요소를 사용하여 구성 요소를 테스트하는 경우 단위 테스트를 실행할 때 발생할 수도 있습니다. 이 경우 해당 구성 요소의 .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();
  }));

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

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

CUSTOM_ELEMENTS_SCHEMA

...에 대한

NO_ERRORS_SCHEMA

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

이제 작동합니다.


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에 추가되지 않습니다.


이 게시물을 읽고 각도 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에 추가하고 나면 사용하는 새로운 커스텀 요소에 이름에 '대시'가 있는지 확인하십시오.


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

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

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

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

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가 필요하지 않으며 오류가 없으며 문제가 없습니다.

So If You were like me and did not want to add CUSTOM_ELEMENTS_SCHEMA to the module - using your component this way does not generates errors and is more clear.

For more info about this issue - https://github.com/angular/angular/issues/11251

For more info about Angular content projection - https://blog.angular-university.io/angular-ng-content/

You can see also https://scotch.io/tutorials/angular-2-transclusion-using-ng-content


I'd like to add one additional piece of information since the accepted answer above didn't fix my errors completely.

In my scenario, I have a parent component, which holds a child component. And that child component also contains another component.

So, my parent component's spec file need to have the declaration of the child component, AS WELL AS THE CHILD'S CHILD COMPONENT. That finally fixed the issue for me.


With components containing Angular Material, a similar error came up with my unit tests. As per @Dan Stirling-Talbert's answer above, added this to my component .spec file and the error was cleared from my unit tests.

Import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'

Then add the schema in the generated beforeEach() statement:

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

My Karma error was: If 'mat-panel-title' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.


That didn't work for me (using 2.0.0). What worked for me was importing RouterTestingModule instead.

I resolved this by importing RouterTestingModule in spec file.

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

  beforeEach(() => {

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

    });

For me, I needed to look at :

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

This means that your component isn't included in the app.module.ts. Make sure it's imported and then included in the declarations section.

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

Did you use the webpack... if yes please install

angular2-template-loader

and put it

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

참고URL : https://stackoverflow.com/questions/39428132/custom-elements-schema-added-to-ngmodule-schemas-still-showing-error

반응형