可以通过在自定义元素中定义Input属性并使用JSON.parse()方法将其转换为对象来解决问题。代码示例如下:
在app.module.ts中声明自定义元素:
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { createCustomElement } from '@angular/elements';
import { MyComponent } from './my.component';
@NgModule({
declarations: [MyComponent],
imports: [BrowserModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
entryComponents: [MyComponent]
})
export class AppModule {
constructor() {
const element = createCustomElement(MyComponent, { injector: injector });
customElements.define('my-element', element);
}
ngDoBootstrap() {}
}
在my.component.ts中定义Input属性并解析JSON字符串:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'my-component',
template: `
{{ data.title }}
{{ data.text }}
`
})
export class MyComponent implements OnInit {
@Input() jsonInput: string;
data: any;
ngOnInit() {
this.data = JSON.parse(this.jsonInput);
}
}
在HTML中使用自定义元素并传递JSON字符串作为属性:
注意:在传递JSON字符串作为属性时需要使用单引号将其包裹。