将自定义元素和属性添加到编译器架构 [英] Add custom elements and attributes to compiler schema

查看:104
本文介绍了将自定义元素和属性添加到编译器架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

组件模板中有一些自定义元素和属性(在此示例中,它们由第三方非角度代码使用):

There are some custom elements and attributes in component template (in this example they are used by third-party non-Angular code):

<foo></foo>
<div data-bar="{{ bar }}"></div>

它们会导致编译器错误:

They cause a compiler error:

Template parse errors:
'foo' is not a known element:
1. If 'foo' is an Angular component, then verify that it is part of this module.
2. If 'foo' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
    [ERROR ->]<foo></foo>
    <div data-bar="{{ bar }}"></div>
  "): App@1:4
Can't bind to 'bar' since it isn't a known property of 'div'. ("
    <foo></foo>
    <div [ERROR ->]data-bar="{{ bar }}"></div>
  ")
...

如何将foo元素和data-bar属性添加到编译器模式?

How can foo element and data-bar attribute be added to compiler schema?

NO_ERRORS_SCHEMA不可选项,因为将其他未知元素和属性列入白名单是不可取的.

NO_ERRORS_SCHEMA is not an option because it is not desirable for other unknown elements and attributes to be whitelisted.

推荐答案

您可以尝试像这样覆盖DomElementSchemaRegistry:

You can try to override DomElementSchemaRegistry like this:

import { DomElementSchemaRegistry, ElementSchemaRegistry } from '@angular/compiler'
import { SchemaMetadata } from '@angular/core';

const MY_DOM_ELEMENT_SCHEMA = [
  'foo'
];

const MY_CUSTOM_PROPERTIES_SCHEMA = {
  'div': {
    'bar': 'string'
  }
};

export class CustomDomElementSchemaRegistry extends DomElementSchemaRegistry {
  constructor() {
    super();
  }

  hasElement(tagName: string, schemaMetas: SchemaMetadata[]): boolean {
    return MY_DOM_ELEMENT_SCHEMA.indexOf(tagName) > -1 || 
         super.hasElement(tagName, schemaMetas);
  }

  hasProperty(tagName: string, propName: string, schemaMetas: SchemaMetadata[]): boolean {
    const elementProperties = MY_CUSTOM_PROPERTIES_SCHEMA[tagName.toLowerCase()];
    return (elementProperties && elementProperties[propName]) || 
        super.hasProperty(tagName, propName, schemaMetas);
  }
}

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [{ provide: ElementSchemaRegistry, useClass: CustomDomElementSchemaRegistry }]
});

柱塞示例

Plunker Example

这篇关于将自定义元素和属性添加到编译器架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆