繁体   English   中英

Angular 用父组件动作改变子组件模板

[英]Angular change child component template with parent component action

我正在尝试创建一个子组件(它是一个表单),它出现在模态的父组件中。

表单(子组件)必须根据父级中选择的类型通过几个按钮(每个按钮是不同的类型)进行更改。

单击按钮时,子组件必须根据父组件中选择的类型修改表单。 表单控件正确更改,但模板未修改。 代码如下:

打开模态并调用子组件的父方法

  show(value: string){
    this.type = value;
    this.entityFormComponent.type = this.type;
    this.entityFormComponent.ngOnInit();

    // Set submitAttemp to false for the new form
    this.entityFormComponent.submitAttemp = false;

    this.contentModal.show();
  }

子组件的方法ngOnInit

  ngOnInit(): void {
    if(this.creating){
      this.entity = new Entity();
    } else {
      this.entityService.get(this.nameToEdit, this.type)
    }
    // Initialize the form and add the corresponding attributes according to the type
    this.entityForm = new FormGroup({});
    this.entityHelper.getEntityFormAttributes(this.entityForm, this.type, this.entity);
  }

到目前为止,似乎一切都是正确的,每次单击父按钮时生成的表单组就足够了,但是表单的输入没有出现。 它们是通过辅助方法生成的,该方法通过传递的输入的类型和属性返回 true 或 false:

<div class="col-md-6" *ngIf="entityHelper.getEntityInputsAttributes('shadow', type)">

视图中的类型是“未定义”,但在组件中显示正确。 为什么视图不能正确更新类型? 我该怎么做才能更新它?

对于父子组件交互,建议使用 Input 指令。 如果你有不同类型的 forms 你可以使用枚举。 并将每个枚举条目绑定到每个按钮,方法是向按钮添加一个操作,该操作设置一个具有对应类型的属性。 例如:

onClick(type: FormTypes) {
   this.formType = type;
}

你的父模板看起来像

<child-component [typeOfForm]=formType </child-component>

当提供新的 formType 时,您的子组件需要执行更改,因此您需要执行类似的操作

@Input()
set typeOfForm(typeOfForm: FormType) {
   //make the necessary changes on form type change.
}

此外,为了避免手动执行 ngOnInit function 可以用 div 包围您的子组件标签,并使用 typescript 代码上的 boolean 属性显示或不显示它:

<div *nfIf="showForm">
   <child-component [typeOfForm]=formType </child-component>
</div>

这样做你的节目 function 只会将 showForm 属性设置为 true。

希望这会有所帮助,有关组件交互的更多详细信息,我建议您查看此文档Angular 组件交互

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM