gpt4 book ai didi

angular - 将自定义元素和属性添加到编译器模式

转载 作者:太空狗 更新时间:2023-10-29 18:16:12 25 4
gpt4 key购买 nike

组件模板中有一些自定义元素和属性(在本例中它们被第三方非 Angular 代码使用):

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

它们会导致编译器错误:

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 属性添加到编译模式?

NO_ERRORS_SCHEMA 不是一个选项,因为不希望将其他未知元素和属性列入白名单。

最佳答案

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

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

关于angular - 将自定义元素和属性添加到编译器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42953118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com