【问题标题】:angular @Input and data interpolation not working in web components角度 @Input 和数据插值在 Web 组件中不起作用
【发布时间】: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 中放入一个字符串值(即&lt;custom-h1 text="Custom header string"&gt;&lt;/custom-h1&gt;),我可以看到正确的输出,即“自定义标题字符串”。

有什么想法或建议吗?或参考?谢谢。

【问题讨论】:

    标签: angular typescript interpolation web-component


    【解决方案1】:

    我认为这就是这里的解释:https://github.com/angular/angular/issues/29050。如果你 console.log() 你在 ngOnChanges() 钩子中的变量你会得到正确的值,但在 ngOnInit() 中它们仍然是未定义的。使用自定义元素时,挂钩的执行顺序会发生变化。这就是为什么在你的它是未定义的。就我而言,我仍在寻找如何强制 ngOnChanges() 先运行然后再运行 ngOnInit() 但还没有运气。

    这样做:

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

    看到这个:Angular Elements: @Input decorator not working with variables

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-15
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      相关资源
      最近更新 更多