angular@输入和数据插值在web组件中不起作用



我有一个web组件库,将在不同的角度项目中使用。我使用@angular/elements将我的组件转换为可重用的元素,然后使用http服务器为其提供服务。

我创建的一个组件是自定义h1:

h1组件.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; }
}

h1component.html

<h1>{{ text }}</h1>

app.module.ts中,我将自定义元素声明为

const h1El = createCustomElement(H1Component, {
injector: this.injector
});
customElements.define('custom-h1', h1El);

我的应用程序是根据https://angular.io/guide/elements

在完成所有组件后,我通过创建另一个有角度的应用程序来测试它们,并将环境设置为加载脚本。然而,这是我注意到我的自定义组件没有采用@Input值的时候。

在我的新应用程序中:

应用程序组件.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>

在我的新应用程序和组件库上的http服务器上运行ng-serve之后自定义标题";。然而,我没有看到任何结果。

如果我在text(即<custom-h1 text="Custom header string"></custom-h1>(中放入一个字符串值自定义标题字符串";。

有什么想法或建议吗?还是参考?非常感谢。

我想这就是这里的解释:https://github.com/angular/angular/issues/29050.如果你在ngOnChanges((钩子中控制台.log((你的变量,你会得到正确的值,但在ngOnInit((中它们仍然是未定义的。使用自定义元素时,钩子执行更改的顺序。这就是为什么在你的书中它是未定义的。在我的情况下,我仍然在寻找如何强制ngOnChanges((先运行,然后运行ngOnInit((,但还没有成功。

也是如此

ngOnChanges(): void {
this._text = text;
}

请参阅:Angular Elements:@Input decorator不使用变量

也许这会有所帮助<custom-h1 [text]="header"></custom-h1>

最新更新