【问题标题】:Angular web component @Input with variable带有变量的Angular Web组件@Input
【发布时间】:2021-03-25 13:09:02
【问题描述】:

https://angular.io/guide/elements

在询问之前,我尝试自己寻找解决方案,但我无法解决我的问题。 我有一个 Web 组件(例如 <test-component></test-component>) 对于初始化,我需要将一些参数传递给它(例如some-string-url)。 当我尝试这样做时,<test-component some-string-url="https://example.com"></test-component> 一切正常,但是对于每个网站或应用程序,该参数应该是动态的,所以当我尝试这样做时: <test-component [some-string-url]="someVariable"></test-component><test-component some-string-url="{{ someVariable }}"></test-component> 它不起作用。我发现它的唯一方法是创建组件并将其附加到 div 中:

  const widget = document.createElement('test-component');
  widget.setAttribute('some-string-url', this.exampleUrl);
  document.getElementById('widget-container').append(widget);

但是我可以使用另一种方式来传递参数吗?

附: ngOnChanges() 没有看到任何变化,根本没有触发。

更新:___________________________________________

我需要从我的 Web 组件 (https://angular.io/guide/elements) 中的变量中获取 @Input 属性,例如 <test-component [some-string-url]="someVariable"></test-component> 应该让我在我的 Web 组件中获得 some-string-url

目前,当我尝试在 onInit 中获取 some-string-url 时,我得到了 undefined,经过检查后。

类似的问题,但没有解决方案Angular Elements: @Input decorator not working with variables

【问题讨论】:

  • 分享test-component的来源。
  • it doesn't work 你能指定吗?你期待什么/发生了什么?你写的应该有效。当您尝试“过早”使用此变量时,通常会出现问题,然后将其传递给组件。请出示代码。
  • 能否分享一下你的web组件的代码。
  • 对于使用@Input 设置的值,我建议使用setter 形式,因为您不知道何时该值被填充并且ngOnInit 为时过早。最安全的是这样做:@Input set someStringUrl(value: string) { [...] }。此外,每次更改值时都会调用 setter,这有时很有用

标签: angular angular-elements


【解决方案1】:

我不确定为什么它对你不起作用,这两种绑定格式都应该起作用。

这是working example

test.component.ts

export class TestComponent {

  @Input() someStringUrl: string;

}

app.component.html

<test-component [someStringUrl]="someVariable"></test-component>

<button (click)="increaseCounter()">Increase Counter</button>

app.component.ts

export class AppComponent  {
  private counter = 1;

  get someVariable() { 
    return `http://www.fake-address.com/${this.counter}`; 
  }

  increaseCounter() {
    this.counter++;
  }
}

【讨论】:

猜你喜欢
  • 2018-03-26
  • 2018-09-29
  • 1970-01-01
  • 2021-11-08
  • 2022-07-28
  • 1970-01-01
  • 2016-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多