首页 > 解决方案 > 如何动态重新加载自定义组件并为其传递新参数?

问题描述

另一个新手 Angular 问题。我有 3 个选项。When an option in the select is selected, I want the value of the option to be passed to the id argument of my custom component and for that component to refresh itself and display the value of the argument passed to it. 目前,当我将参数的值重置为 mycustomcomponent 时,没有任何反应。

app.component.html

<select (change)="onDoSomethingWithChange($event.target.value)">
  <option value="1">Value 1</option>
  <option value="2">Value 2</option>
  <option value="3">Value 3</option>
</select>

<mycustomcomponent #MyCustomComp [id]=0></mycustomcomponent>

app.component.ts

export class AppComponent implements OnInit {
  
@ViewChild('MyCustomComp', {static: false}) myCustomComp: MyCustomComponent;

 public onDoSomethingWithChange(id : number):void
 {
    this.myCustomComp.id = id
 }
}

mycustomcomponent.component.ts(该组件将简单地获取传递给它的 id 值并显示它。)

export class MyCustomComponent implements OnInit {

  @Input() id: number;
}

mycustomcomponent.component.html

 You passed an id of value {{id}}

标签: angularcomponents

解决方案


您不需要使用“ViewChild”来将选定的值传递给子组件。您可以在父组件中有一个属性来保存“选定值”,并且在每次更新选定值时,您都会更新该值。此属性可以作为输入传递给您的子组件。

堆栈闪电战示例


推荐阅读