Pra*_*nth 7 javascript typescript custom-element angular angular7
我使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我在 app.component.html 中引用了这些自定义元素,如下所示:
<footer-element footer-data="footerInputData"></footer-element>
Run Code Online (Sandbox Code Playgroud)
这个 footerInputData 在我的 app.component.ts 文件中作为字符串引用。
export class AppComponent {
footerInputData: any = {title: "Page Title"};
}
Run Code Online (Sandbox Code Playgroud)
在我的自定义元素的 HTML 中,我使用插值来显示作为输入传递给它的数据。
<div class="nav-list-wrap">
{{footerData}}
</div>
Run Code Online (Sandbox Code Playgroud)
当页面加载时,我没有看到显示的对象。相反,它显示的是“footerInputData”。
如何让我的自定义元素从我的 app.component.ts 文件中获取数据,而不是将数据显示为字符串。
另外,JSON 对象可以传递给我的自定义元素吗?
[]您中应该有一个footer-data,并且可能需要一个changeDetectRef来重新检查更改后的值。
步骤1
ng new testing
第2步
ng g c footer
步骤 3 输入app.module.ts
import { createCustomElement } from '@angular/elements';
import { FooterComponent } from './footer/footer.component';
...
@NgModule({
declarations: [AppComponent, FooterComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent],
entryComponents: [FooterComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule {
constructor(private injector: Injector) {
const customElement = createCustomElement(FooterComponent, { injector });
customElements.define('some-component', customElement);
}
ngDoBootstrap() { }
}
Run Code Online (Sandbox Code Playgroud)
步骤 4 输入app.component.html
<some-component [data]="footerInputData"></some-component>
步骤 5 输入app.component.ts
...
export class AppComponent {
footerInputData = {"testing": "abc"}
}
Run Code Online (Sandbox Code Playgroud)
步骤 6 输入footer.component.ts
import { Component, OnInit, Input, AfterViewChecked } from '@angular/core';
import { ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.scss']
})
export class FooterComponent implements OnInit, AfterViewChecked {
@Input() public data: any;
displayedData = ""
constructor(
private cdRef:ChangeDetectorRef
) { }
ngOnInit() {
}
ngAfterViewChecked() {
this.displayedData = this.data
this.cdRef.detectChanges();
}
}
Run Code Online (Sandbox Code Playgroud)
步骤 7 输入footer.component.html
<p>
{{ displayedData | json }}
</p>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6359 次 |
| 最近记录: |