【发布时间】:2020-11-11 07:43:42
【问题描述】:
我有一个 Web 组件库,可用于不同的 Angular 项目。我正在使用 @angular/elements 将我的组件转换为可重用元素,然后使用 http-server 为其提供服务。
我创建的一个组件是自定义 h1:
h1-component.ts
import { Component, Input, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-h1',
templateUrl: './h1.component.html',
styleUrls: ['./h1.component.scss'],
encapsulation: ViewEncapsulation.ShadowDom
})
export class H1Component {
private _text: string = '';
@Input() set text(text: string) { this._text = text; }
get text(): string { return this._text; }
}
h1-component.html
<h1>{{ text }}</h1>
在我的 app.module.ts 中,我将自定义元素声明为
const h1El = createCustomElement(H1Component, {
injector: this.injector
});
customElements.define('custom-h1', h1El);
我的应用是根据https://angular.io/guide/elements设置的
完成所有组件后,我继续通过创建另一个 Angular 应用程序来测试它们,设置我的环境以加载我的脚本。但是,此时我注意到我的自定义组件没有采用我的 @Input 值。
在我的新应用程序中:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
header = "Custom header";
}
app.component.html
<custom-h1 text="{{ header }}"></custom-h1>
在我的新应用程序上运行 ng serve 并在我的组件库上运行 http-server 后,我应该会看到“自定义标头”。但是,我没有看到任何结果。
如果我在 text 中放入一个字符串值(即<custom-h1 text="Custom header string"></custom-h1>),我可以看到正确的输出,即“自定义标题字符串”。
有什么想法或建议吗?或参考?谢谢。
【问题讨论】:
标签: angular typescript interpolation web-component