【问题标题】:Edit variable passed into an Angular 8 Web component传递给 Angular 8 Web 组件的编辑变量
【发布时间】:2020-01-08 14:08:05
【问题描述】:

我使用 Angular 8 创建了一个 Web 组件(我们将其命名为测试组件),它接收输入并将其显示给浏览器(test.component.html 文件)

<h3>{{title}}</h3>

test.component.ts 文件接收输入并将其记录在控制台中

export class TestComponent implements OnInit {
  @input() title;

  constructor() {}
  ngOnInit() {console.log(this.title)}
}

使用 Web 组件的独立应用程序的index.html 如下所示:

<test-component title="this is a string"></test-component>

它正确显示字符串并将其记录到控制台。

当我在现有的 Angular 应用程序中使用 Web 组件时,就会出现问题。我要传递给 Web 组件的变量是动态的,并且来自现有应用程序的组件。我尝试以两种不同的方式将它传递到一个已经存在的组件(例如existing-application.component.html)中:

<test-component [title]="titleVariable"></test-component>

<test-component title={{titleVariable}}></test-component>

其中 titleVariable 在关联的existing-application.component.html 文件中定义,如下所示

export class ExistingApplicationComponent implements OnInit {

  titleVariable= 'this is a string';

  constructor() {}
  ngOnInit() {}
}

这里,虽然 h1 html 元素正确显示了字符串,但 console.log 是未定义的。

我还尝试将它(在 Web 组件中)记录在 ngAfterViewInit() 而不是 ngOnInit() 中,但没有任何运气。

有人知道为什么会发生这种情况吗? 提前感谢您的宝贵时间

【问题讨论】:

  • 这能回答你的问题吗:stackoverflow.com/questions/34396684/…
  • 非常感谢@Layera,虽然它没有直接回答我的问题,但它确实给了我其他的尝试。
  • titleVariable 的值在您的尝试中是否发生了变化,或者是否已修复?
  • titleVariable 的值是固定的,但我需要在将其显示到 h1 之前对其进行解析和编辑,我尝试使用 ngAfterViewChecked() 生命周期,但它运行了多次。

标签: angular angular8 web-component


【解决方案1】:

问题在于生命周期挂钩。当你想访问input() 属性时,你需要ngOnChanges() life-cylce hook。

NgOnChanges:“当 Angular(重新)设置数据绑定输入属性时响应。该方法接收当前和先前属性值的 SimpleChanges 对象。 在 ngOnInit() 之前以及每当一个或多个数据绑定输入属性更改时调用。 "

【讨论】:

  • 但是如果你想改变属性值,你可以使用pipeangular.io/guide/pipes
  • ngOnChanges() 生命周期有效,但日志记录完成两次,第一次未定义,第二次正确记录。
  • 因为ngOnChanges() 运行多次,在ngOnInit() 之前和input() 之后重新设置。如果要访问该属性并进行修改,请在 HTML 模板中使用pipes。
  • Pipe 是一个非常好的主意,但是因为我正在构建一个 Web 组件,所以我也需要它在独立的应用程序中工作。例如,在没有角度的空 index.html 文件中包含自定义元素无法与管道一起使用。
  • 哦,那么您可以在input 函数中检查input 值,在带有if 语句的changes 对象中,您可以像这样更改值:export class HelloComponent { @Input() name: string; ngOnChanges(changes: SimpleChanges) { if (changes &amp;&amp; changes.name) { this.name = 'Excepted value'; } } }
猜你喜欢
  • 1970-01-01
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2021-05-05
  • 2019-09-15
  • 2017-05-06
相关资源
最近更新 更多