【问题标题】:Angular change child component template with parent component action具有父组件操作的角度更改子组件模板
【发布时间】:2020-09-02 07:15:35
【问题描述】:

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

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

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

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

  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);
  }

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

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

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

【问题讨论】:

    标签: javascript angular components


    【解决方案1】:

    对于父子组件交互,建议使用 Input 指令。 如果您有不同类型的表单,则可以使用枚举。并通过向按钮添加一个操作来将每个枚举条目绑定到每个按钮,该操作将属性设置为其对应的类型。例如:

    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 函数,可以使用 div 围绕您的子组件标签,并在 typescript 代码上显示或不显示布尔属性,如下所示:

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

    这样做您的 show 函数只会将 showForm 属性设置为 true。

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

    【讨论】:

      猜你喜欢
      • 2020-06-18
      • 2020-06-28
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      相关资源
      最近更新 更多