我使用 CUSTOM_ELEMENTS_SCHEMA 在 Angular 7 中创建了一个自定义元素。 我的 app.module.ts 如下:
export class AppModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
this.registerCustomElements();
}
registerCustomElements() {
const HeaderElement = createCustomElement(AppComponent, {
injector: this.injector
});
const FooterElement = createCustomElement(BcAngFooterComponent, {
injector: this.injector
});
customElements.define("header-element", HeaderElement);
customElements.define("footer-element", FooterElement);
}
}
我在我的 app.component.html 中引用了这些自定义元素,如下所示:
<footer-element footer-data="footerInputData"></footer-element>
此 footerInputData 在我的 app.component.ts 文件中作为字符串引用。
export class AppComponent {
footerInputData: any = {title: "Page Title"};
}
在我的自定义元素的 HTML 中,我使用插值来显示作为输入传递给它的数据。
<div class="nav-list-wrap">
{{footerData}}
</div>
当页面加载时,我没有看到显示的对象。相反,它显示“footerInputData”。
如何让我的自定义元素从我的 app.component.ts 文件中获取数据,而不是将数据显示为字符串。
此外,JSON 对象可以传递到我的自定义元素吗?
最佳答案
自定义元素旨在在 Angular 包装器外部使用,即使您可以在 Angular 包装器内部使用它们。 当你在 Angular 包装器之外使用它们时,你需要像这样使用它
<footer-element name='{"title": "Page Title"}'></footer-element>
属性值应该被字符串化,如果你传递的是 json,json 字符串应该被严格格式化。
当您在 Angular 包装器中使用它时,您可以将它与 Angular 选择器一起使用,并且可以像旧方法一样传递数据。
<app-custom [name]="name"></app-custom>
//ts file
name = {title:"this is title"}
自定义component.ts文件
@Component({
selector: 'app-custom',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@Input() name: any;
}
应用程序模块.ts
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, MainComponent],
entryComponents:[
AppComponent, MainComponent
]
})
export class AppModule {
constructor(private injector: Injector) { }
ngDoBootstrap() {
//bootstraping angular app
const AppElement = createCustomElement(MainComponent, { injector: this.injector });
customElements.define('my-app', AppElement);
//bootstraping custom element
const el = createCustomElement(AppComponent, { injector: this.injector });
customElements.define('footer-element', el);
}
}
关于javascript - 如何将 JSON 对象传递给 Angular 自定义元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54662669/