【问题标题】:Not a known element in angular even when using NO_ERRORS_SCHEMA即使使用 NO_ERRORS_SCHEMA 也不是角度的已知元素
【发布时间】:2018-12-21 20:06:01
【问题描述】:

我有和 Angular Popup Component 使用如下 (Online Example):

<popup>
  <anchor>
    Menu        
  </anchor>
  <window>
    <ul>
      <li>Item 1</li>           
      <li>Item 2</li>
    </ul>
  </window>
</popup>

组件模板是:

<a class="anchor" (click)="toggle()">
  <ng-content select="anchor"></ng-content>
</a>
<div class="window" [hidden]="!active">
  <ng-content select="window"></ng-content>
</div>

我收到以下错误:

Template parse errors: 'anchor' is not a known element:    
1. If 'anchor' is an Angular component, then verify that it is part of this module.    
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. 

弹出模块已经有 NO_ERRORS_SCHEMA:

import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';  
import { PopupComponent} from './popup.component';

@NgModule({  
  declarations: [PopupComponent],      
  imports: [CommonModule],  
  exports: [PopupComponent],
  schemas: [NO_ERRORS_SCHEMA]
})

export class PopupModule {}

而 PopupComponent 是:

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

@Component({
  selector: 'popup',
  templateUrl: './popup.component.html'
})

export class PopupComponent {
  @Input() active: boolean = false;
  toggle() {
    this.active = !this.active;
  }
}

我错过了什么?

【问题讨论】:

    标签: angular angular6 angular7


    【解决方案1】:

    您将anchor 元素放置在AppComponent 模板中。 AppComponentAppModule 中定义

    所以将NO_ERRORS_SCHEMA 添加到该模块:

    @NgModule({  
      ...
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    
    export class AppModule {}
    

    Forked Stackblitz

    【讨论】:

    • 我明白了……我误解了。我虽然 NO_ERRORS_SCHEMA 用于定义组件的模块,但它用于使用该组件的模块。所以这可能是个坏主意,因为我需要在所有正确使用该组件的地方都有 NO_ERRORS_SCHEMA?
    • 只有在测试中才鼓励使用 NO_ERRORS_SCHEMA。为什么要使用这样的标签?
    • I would need to have NO_ERRORS_SCHEMA in all places where this component is used correct? 由于 Angular 在编译模板时正在寻找传递模块范围,因此您必须将其添加到每个模块中,其中您有一个在模板中具有该标签的组件
    • 我刚决定使用一个属性。感谢您的帮助和解释。刚刚标记为答案
    猜你喜欢
    • 2018-04-10
    • 2017-09-26
    • 1970-01-01
    • 2020-09-25
    • 2021-11-29
    • 1970-01-01
    • 2021-01-22
    • 2017-06-30
    • 2021-01-13
    相关资源
    最近更新 更多